Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

767
Visualizações
how to store and get access_token in NextJS SSR

I use NextJS with ServerSide Rendering

I use an authentication service with access_token (JWT)

I can't store access_token in the localStorage because it's not available in the getServerSideProps

so I put access_token in an httpOnly cookie to be available on the server.

I have some requests on the server and some on the client, so I need to get the access_token in two ways, on the server from req.headers.cookie and on the client from document.cookie

I want to wrtie axios interceptors to add access_token to the every request.

this works for the client-side, but what can I do for the server-side ?

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;
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You may want to use nookies

From 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: '/' })

    ...

}

From API route

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: '/' })

    ...
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda