node.js - 如何在 NextJS SSR 中存储和获取 access_token
问题描述
我将 NextJS 与服务器端渲染一起使用
我使用带有 access_token (JWT) 的身份验证服务
我无法将 access_token 存储在 中,localStorage
因为它在getServerSideProps
所以我把 access_tokenhttpOnly cookie
放在服务器上可用。
我在服务器上有一些请求,在客户端上有一些请求,所以我需要通过两种方式获取 access_token,从服务器req.headers.cookie
和客户端获取document.cookie
我想编写 axios 拦截器以将 access_token 添加到每个请求中。
这适用于客户端,但我可以为服务器端做什么?
import axios from 'axios';
const _axios = axios.create();
axiosInstance.interceptors.request.use(function (config) {
let token;
// check if it's on the client-side
if(typeof document !== 'undefined')
token = getToken(document.cookie);
// how to check for server-side and how to get cookie ?
return {
...config,
headers: {
'Authorization': `Bearer ${token}`
}
};
}, function (error) {
return Promise.reject(error);
});
export default axiosInstance;
解决方案
你可能想使用nookies
从 getServerSideProps
export async function getServerSideProps(ctx) {
//Parse cookies from request header
const cookies = nookies.get(ctx)
//Set cookies on response header
nookies.set(ctx, 'key', 'token', { path: '/' })
...
}
从 API 路由
export default function handler(req, res) {
//Parse cookies from request header
const cookies = nookies.get({ req })
//Set cookies on response header
nookies.set({ res }, 'key', 'token', { path: '/' })
...
}
推荐阅读
- git - 在错误的分支上工作尝试了 git stash 但没有工作
- javascript - javascript中的特殊加法
- html - 为什么 CSS 预加载不起作用或根本不应用样式?
- ios - SwiftUI 和函数 - 在范围内找不到“viewContext”
- typescript - 打字稿中的联合类型和鸭子类型
- java - 如何保存高分值并在应用程序关闭时加载它
- flutter - Flutter:如何共享 statefull 小部件的实例?
- google-bigquery - 如何在 AWS Glue 到 BigQuery 连接器中指定项目 ID?
- python - 指定运行 pip 卸载时应删除的文件?
- node.js - \[express-ntlm\] 不存在授权标头