首页 > 解决方案 > 如何在 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;

标签: node.jsreactjsaxiosjwtnext.js

解决方案


你可能想使用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: '/' })

    ...
}

推荐阅读