How access server side cookies in a axios intercepor and outside of getServerSideProps()

Viewed 215

In my nextjs app, I created a separate file for my axios interceptors and I'm making a request in getServerSideProps() which needs to have a Authorization header with some access token. I'm doing the logic for attaching headers inside mu interceptors but I need to access the cookie outside of getServerSideProps() and in my interceptor. Is there a way to achieve this behavior?

1 Answers

Late answer but may be useful for someone. You'll need to create an API route to retrieve the cookie as usually you'll need to pass the req and res to the cookie lib you're using like cookies-next.

So you create a route like /api/token and then place a code like this:

import { getCookie } from 'cookies-next';
import type { NextApiRequest, NextApiResponse } from 'next';

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const token = getCookie('site-jwt', { req, res });
  res.status(200).json({ token });
}

and then in your interceptor, you do a fetch

const { token } = await fetch('/api/token').then(r => r.json())
Related