[英]NextJS next-auth get session always null
Can't get the session data using getSession({req}) on a api call?无法在 api 调用中使用 getSession({req}) 获取会话数据? useSession() on a component is working fine.
组件上的 useSession() 工作正常。
package versions: nextjs@12.01, next-auth@4.3.1包版本:nextjs@12.01、next-auth@4.3.1
issue: api/lists.ts:问题:api/lists.ts:
import prisma from "../../../lib/prisma";
import { getSession } from "next-auth/react"
export default async (req: NextApiRequest, res: NextApiResponse) => {
const session = await getSession({ req });
console.log('session data is always null', session);
nexuauth.js config file: nexuauth.js 配置文件:
callbacks: {
session: async ({ session, user, token }) => {
if (session?.user) {
session.user.id = user.id;
}
// console.log('session callback', session);
return session;
},
},
session: { strategy: "database" },
_app.js file: _app.js 文件:
function MyApp({ Component, ...pageProps }) {
return (
<SessionProvider session={pageProps.session} refetchInterval={5 * 60}>
<Main>
<Component {...pageProps} />
</Main>
</SessionProvider>
)
}
export default MyApp
on a login.js file (working fine):在 login.js 文件上(工作正常):
export default function Login() {
const { data: session } = useSession()
Session depends on cookies, your browser automatically sends the cookies.会话取决于 cookie,您的浏览器会自动发送 cookie。 So
useSession()
, which is on client side/browser always work.因此,在客户端/浏览器上的
useSession()
始终有效。 But when you use getSession
cookies are not present automatically , we need to set them manually ( github issue )-但是当您使用
getSession
cookie 时不会自动出现,我们需要手动设置它们( github 问题)-
const response = await fetch(url, {
headers: {
cookie: req.headers.cookie || "",
},
});
To add these automatically you can perhaps plug into interceptors
( axios , fetch ) or make a wrapper
function.要自动添加这些,您可以插入
interceptors
( axios , fetch )或制作wrapper
函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.