我有以下代码:
export const requireAuth = (gssp: GetServerSideProps) => {
return async (ctx: GetServerSidePropsContext) => {
const { req } = ctx;
let session = null;
if (req?.headers?.cookie) {
session = await getSession(req?.headers?.cookie);
};
if (!session) {
return {
redirect: {
permanent: false,
destination: '/login',
},
};
};
return await gssp(ctx);
};
};
我还尝试在 await gssp(ctx) 中返回 session ,我对 NextJS 还很陌生,我无法找到任何相关信息。
当前方法允许我按以下方式使用该组件:
export const getServerSideProps: GetServerSideProps = requireAuth(async _ctx => {
let account;
let stats = {};
if (_ctx?.req?.headers?.cookie) {
account = await getSession(_ctx?.req?.headers?.cookie);
}
try {
const X = fetchSomeData...;
} catch (error) {
console.log('Pages/Index Fetching Error: ', error);
}
return {
props: {
account: account,
data: X,
navbar: true,
footer: true,
},
};
});
与其他 HOR 方法相比,它允许在使用它的页面上添加额外的逻辑。
有什么方法可以在主 requireAuth
组件中返回 session ,而不是在每个页面上获取它?
最佳答案
您可以控制高阶函数传递给实际 gssp
函数的内容,因此您只需在 ctx
对象中传递 session 即可。
export const requireAuth = (gssp: GetServerSidePropsWithSession) => {
return async (ctx: GetServerSidePropsContext) => {
const { req } = ctx;
const session = req?.headers?.cookie ? await getSession(req?.headers?.cookie) : null;
if (!session) {
return {
redirect: { permanent: false, destination: '/login' }
};
};
const ctxWithSession = { ...ctx, session };
return await gssp(ctxWithSession);
};
};
然后,您可以在 getServerSideProps
代码中访问session
。
interface GetServerSidePropsContextWithSession extends GetServerSidePropsContext {
session?: Session;
}
type GetServerSidePropsWithSession<P extends { [key: string]: any } = { [key: string]: any }> = (
context: GetServerSidePropsContextWithContext
) => Promise<GetServerSidePropsResult<P>>;
export const getServerSideProps: GetServerSidePropsWithSession = requireAuth(async _ctx => {
const account = _ctx.session;
// Remaining code...
});
请注意,您需要扩展 GetServerSideProps
类型以获取 session
字段。
关于typescript - 在 Next.js 中的高阶身份验证组件中返回附加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72010291/