Expired access/id tokens nextjs

Hi, i’ve been trying to use the nextjs-auth0 package securing a page (both with pages & app routers) with withPageAuthRequired and useUser.

What i do:

  • Standard login with withPageAuthRequired using the universal login
  • Once the page loads i send a request to a backend (which checks the token using jwks)
  • The auth fails saying token is expired

Both return that the user is authenticated but when i try to use the access/id token it says it’s expired (Works fine for the day i logged in, but the day after it says the token is expired, and it only refreshes when i log out and log back in).

I’ve tried setting the handle profile to refetch as stated here, but it did not work.

I send my token to my backend by using a path in nextjs as a proxy (I would also like to ask if using this approach there is any difference in sending id token vs access token).

import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0'
import axios from 'axios'

export default withApiAuthRequired(async function quoteProxy(req, res) {
	const session = await getSession(req, res)

	// check if user is logged in, check body, use body to post to quote backend, return quote backend result (or error)
	let user = session && session.user

	if (user) {
		const { path } = req.query

		try {
			const response = await axios({
				method: req.method,
				headers: {
					...req.headers,
					authorization: `Bearer ${session.idToken}`,
					'transfer-encoding': '',
				},
				data: req.body,
				url: `${process.env.BACKEND_SERVER_URL}/${path.join('/')}`,
			})
			res.status(response.status).json(response.data)
		} catch (error) {
			let { request, ...rest } = error
			res.status(error.response.status).json(error.response.data)
		}
	}
})

Hi @luigiC,

Welcome to the Auth0 Community!

It seems like you were using an expired access token, where the access token possibly had a 1 day token lifetime, to access a secure page.

What you will need to do is check if there user’s session has expired and prompt the user to re-authenticate.

Let me also add that refetch: true is used to return the user profile information based on the existing session information. Hence, why, you are still required to log in again to get access to the protected resource.

Finally, there is a difference in sending an ID or Access token. You will want to send the Access Token since it contains these registered claims regarding the authentication.

Let me know how this goes for you.

Thanks,
Rueben

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.