I am working with a Next.js frontend and an Express backend. I need a solution to automatically create and reuse a user’s access token until it expires. I believe there might be a way to achieve this using the SDK, but I haven’t been able to find it in the past few weeks of working with Auth0 and Next.js.
Currently, I’m using getAccessToken
to securely send requests to my API. While this works, I’ve noticed that this method generates a new access token each time and does not store anything in the browser. Should I be handling this myself by storing the token in local storage or a cookie, or does Auth0’s Next.js SDK provide a built-in solution for this? I also tried using getSession
, but it did not refresh the access token automatically.
Here is an example page.jsx making a request
// 'use server';
import { getAccessToken } from '@auth0/nextjs-auth0';
const apiServerUrl = process.env.API_SERVER_URL;
const fetchProtectedData = async () => {
const { accessToken } = await getAccessToken();
const response = await fetch(`${apiServerUrl}/protected`, {
headers: {
'content-type': 'application/json',
Authorization: `Bearer ${accessToken}`,
},
});
const responseData = await response.json();
return responseData;
};
export default async function ProtectedPage2({ params }) {
const data = await fetchProtectedData(params);
return (
<div>
<UserInfo data={data} />
</div>
);
}
function UserInfo({ data }) {
return (
<div>
<h2>Protected Route</h2>
<ul>
{Object.entries(data).map(([key, value]) => (
<li key={key}>
<strong>{key}:</strong> {value}
</li>
))}
</ul>
</div>
);
}
Here is my middleware.js
import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge';
export default withMiddlewareAuthRequired();
Here is my .env configuration for scope.
AUTH0_SCOPE='openid offline_access email profile'