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