Decorate api requests with Bearer token in NextJS getServerSideProps

Viewed 3641

I am using axios interceptors to decorate all my requests with an Authorization header.

I get the token from @auth0/nextjs-auth0 by using an API route /api/token:

import auth0 from '@/libs/auth0/auth0';
import { AccessTokenResponse } from '@auth0/nextjs-auth0/dist/tokens/token-cache';
import { NextApiRequest, NextApiResponse } from 'next';

export async function getAccessToken(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<AccessTokenResponse> {
  const tokenCache = auth0(req).tokenCache(req, res);
  return tokenCache.getAccessToken();
}

export default async function token(
  req: NextApiRequest,
  res: NextApiResponse
): Promise<void> {
  try {
    const { accessToken } = await getAccessToken(req, res);
    res.status(200).end(accessToken);
  } catch (error) {
    res.status(error.status || 500).end(error.message);
  }
}

The api route works fine on the client side requests and I can see the token being added and requests going through.

const { token } = await axios.get('/api/token');

    const result = {
      ...config,
      headers: {
        Authorization: `Bearer ${data}`,
      },
    };
    return result;

However this does not work for the SSR pages when I use the same axios interceptors.

I tried full qualifying the url like so:

const { token } = await axios.get('http://localhost:3000/api/token');

But this throws an error in the SSR layer:

The user does not have a valid session.

I do not know how to get the token from the token cache to be used in the interceptor for the api calls made via SSR?

Any ideas or similar experience?

1 Answers

Instead of making a request to your API route from the server-side (I'm assuming using getServerSideProps), you should call the getAccessToken function directly to retrieve the token.

import { getAccessToken } from './api/token' // Replace with the path to your API route

export async function getServerSideProps({ req, res }) {
    const { accessToken } = await getAccessToken(req, res);

    // Remaining code
}

Any logic from API routes should be directly used in getServerSideProps, as they both run on the server anyway.

Related