Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

764
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!