getServerSideProps 未通过导入更新数据

getServerSideProps is not updating data with import

我在 NextJS 中遇到 getServerSideProps 问题,无法在页面加载时更新值。从导入的 JSON 文件的数据调用时,它似乎与使用 getStaticProps 具有相同的效果。

这是适用的代码:

/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
}

对于 SSR 页面,可以理解地开始这样做,我将权限传递给 getStaticProps 中的页面,并将这些值传递到这些页面中的 hasPermission() 函数中,以便它们在权限更改时重新验证。然而 getServerSideProps 中没有重新验证选项,因此数据根本没有重新验证。我之前使用过 getInitialProps,但几乎每个人都不赞成这样做,因为它会禁用 ASO。

如何使用 getServerSideProps 使我导入的 json 至少重新生效?

我最终没有使用 json 导入,而是出于其他原因使用了 fs,但是通过在 getServerSideProps:

中使用动态导入解决了这个问题
export async function getServerSideProps(context) {
  const permissions = await import('../db/users.json')
}

也不要犯我将整个权限数据库传递给每个用户的错误,就像在 getStaticProps 中使用 getPermissions 之类的函数将数据传递给 hasPermission页面中的函数。相反,如果用户具有权限,则仅使用 getServerSideProps 提供数据。换句话说,确保您从服务器端保留数据。然后,如果需要,您还可以将个人权限传递给页面,例如显示一条消息说您没有权限。