NextJS搭配next-auth如何将Node.js后端返回的cookie传递到前端
解决方案
问题根源
当前代码仅提取了Node后端响应体的用户数据,丢弃了响应头中携带认证信息的set-cookie字段,且未配置next-auth将该cookie透传给前端。
调整步骤
1. 改造authorize逻辑,提取后端返回的cookie
修改axios请求配置,获取完整响应头,将后端返回的认证cookie和用户数据一并返回:
import axios from 'axios' import NextAuth from 'next-auth' import Providers from 'next-auth/providers' import { NextApiRequest, NextApiResponse } from 'next' const authHandler = NextAuth({ providers: [ Providers.Credentials({ name: 'Credentials', credentials: { email: { label: "Email", type: "email", placeholder: "Your email" }, password: { label: "Password", type: "password",placeholder: "*********" } }, async authorize(credentials:any, req) { try { const res = await axios.post('http://node-app:4200/users/login',credentials, { withCredentials: true // 跨域场景下保证cookie正常返回 }) if(res.status==200) { // 同时返回用户数据和后端下发的cookie return { ...res.data, backendCookies: res.headers['set-cookie'] } } } catch(e:any){ console.log(e.response?.data) } return null } }) ], pages: { signIn: '/auth/login', signOut: '/auth/logout', }, // 新增回调配置,将cookie存入jwt和session callbacks: { async jwt({ token, user }) { // 首次登录时将cookie存入jwt if (user?.backendCookies) { token.backendCookies = user.backendCookies } return token }, async session({ session, token }) { // 将cookie暴露给前端session if (token.backendCookies) { session.backendCookies = token.backendCookies } return session } }, // 新增事件回调,登录成功时直接将cookie写入前端响应头 events: { async signIn({ user, res }) { if (user.backendCookies) { res.setHeader('Set-Cookie', user.backendCookies) } } } }) // 导出包装后的handler,支持操作原生req/res export default (req: NextApiRequest, res: NextApiResponse) => { return authHandler(req, res) }
2. 后续请求注意事项
- 前端直接请求Node后端接口时,需要给axios/fetch设置
withCredentials: true,浏览器会自动携带已存储的认证cookie - 若在
getServerSideProps等服务端逻辑中请求Node后端,需要手动从req.headers.cookie中提取cookie,添加到请求头中再发送
3. 可选TS类型扩展
如果使用TypeScript,需要扩展next-auth的类型定义避免类型报错,在项目的类型声明文件中添加:
import NextAuth from "next-auth" declare module "next-auth" { interface Session { backendCookies: string[] } interface User { backendCookies: string[] } } declare module "next-auth/jwt" { interface JWT { backendCookies: string[] } }
验证
配置完成后重新登录,打开浏览器开发者工具的Application面板,查看Cookie存储,确认Node后端下发的认证cookie已经存在,后续请求即可自动携带完成身份校验。
内容的提问来源于stack exchange,提问作者Ankush Verma
相关产品推荐
相关产品推荐

