【问题标题】:how to store and get access_token in NextJS SSR如何在 NextJS SSR 中存储和获取 access_token
【发布时间】:2021-05-07 12:22:59
【问题描述】:

我将 NextJS 与服务器端渲染一起使用

我使用带有 access_token (JWT) 的身份验证服务

我无法将 access_token 存储在 localStorage 中,因为它在 getServerSideProps 中不可用

所以我将 access_token 放在 httpOnly 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.js reactjs axios jwt next.js


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2023-01-18
      • 2017-11-15
      • 2021-05-12
      • 2020-11-28
      • 2020-08-20
      • 2021-04-09
      • 2019-08-02
      • 2023-03-20
      • 2021-07-31
      相关资源
      最近更新 更多