Hi there,
I am building a server side rendered page that has both an unauthed and authed experience. Our pages are rendered based on data returned from the API. The API determines whether a user is logged in or not using the access token. withApiAuthRequired
and withPageAuthRequired
aren’t relevant to our use case because you can be either logged in or not and successfully make a request to the same endpoint. It sounds like withPageAuthRequired
makes the SSR hold off until isLoading
is false.
The issue we are facing is that the SSR never receives an access token because it fires instantly. It seems the getServerSideProps always fires before the user is fetched, meaning the cookie is never sent in the request. This leads to our pages never being able to have different data based.
Our API endpoint is a proxy that simply forwards our requests:
// /api/<sensitive>/[...proxy].jsx
import { getAccessToken } from "@auth0/nextjs-auth0";
import axios from "axios";
export default async function handler(req, res) {
const { method, body } = req;
const endpoint = req.url.replace("/api/<sensitive>", "");
const EXTERNAL_API_URL = process.env.API_URL;
const { accessToken: newAccessToken } = await getAccessToken(req, res);
const config = {
baseURL: EXTERNAL_API_URL,
url: endpoint,
method,
headers: {
...(accessToken && { Authorization: `Bearer ${accessToken}` }),
},
...(method != "GET" && { data: body }),
};
try {
const response = await axios(config);
return res.status(response.status).json(response.data);
} catch (err) {
return res.status(err.response.status).json(err.response.data);
}
}