I'm having a problem with getServerSideProps
in NextJS not updating values on page load. It seems to be having the same effect as using getStaticProps
when calling from data that is an imported json file.
Here's the applicable code:
/update/[...id].js
import { hasPermission, getPermissions } from '../../lib/permissions'
...
//in the page function I use the ternary to check permission of the user
{ (hasPermission(session.user.email, `${params.id[0]}-edit`, permissions)) ? <HasPerm /> : <NoPerm /> }
...
export async function getServerSideProps(context) {
const params = context.query
const permissions = getPermissions()
return {
props: { params, permissions }
}
}
/lib/permissions.js
import permissions from '../db/users.json'
export function hasPermission(username, group, perm = false) {
if (!perm)
perm = permissions
if (username in perm && perm[username].groups.includes(group)) {
return true
}
if (perm.all.groups.includes(group)) {
return true
}
return false
}
export function getPermissions() {
return permissions
}
For SSR pages that were understandably doing this to begin with, I pass in the permissions to the page in getStaticProps
and pass those values into my hasPermission()
function in those pages so that they are revalidated on permissions change. Yet there is no revalidation option in getServerSideProps
so the data is not revalidated at all. I was using getInitialProps
before but pretty much everyone discourages that because it disables ASO.
How do I use getServerSideProps
such that my imported json is at least revalidated? Thanks
I ended up not using the json import and used fs
instead for other reasons but the issue is resolved by using dynamic imports in the getServerSideProps
:
export async function getServerSideProps(context) {
const permissions = await import('../db/users.json')
}
Also don't make my same mistake of passing the whole permissions database to every user as was being done by using a function like getPermissions
in getStaticProps
to get the data to the hasPermission
function in the page. Instead, only serve data with getServerSideProps
if the user has permission. In other words, ensure you're holding the data back from the server-side. Then you can also pass through an individual's permissions to the page if you need to, like for displaying a message saying you don't have permission.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.