Hi @dpramanik
A bit of background first; When the nextjs-auth0 library crafts an authorization URL it stores a random string as a state parameter within a cookie. Then passes this value with the state attribute to Auth0 during the /authorize call. Once Auth0 completes its events of actions to validate the user, passes the same state parameter back to the application callback URL along with the credentials. Then the SDK validates the returned state parameter with the stored state in the cookie. This mechanism helps to avoid CSRF attacks.
Reviewing the HAR files, when the error happens, the state parameter passed in /authorize call is sent back to the callback URL correctly. So the issue isn’t related to the Auth0 server but either the application code or the nextjs-auth0 library.
https://[redacted].us.auth0.com/authorize?..redacted..&state=eyJub25jZSI6IjdkNDNhOTlmMTc1Yzc3MDhjZTU5MDNhNGZiMmI3OTE3In0
https://[redacted]/api/auth/callback?code=zyQx3qFDzlJgcVQ7&state=eyJub25jZSI6IjdkNDNhOTlmMTc1Yzc3MDhjZTU5MDNhNGZiMmI3OTE3In0
This specific error message is thrown from this line of the code.
// Require that we have a state.
const state = cookies['a0:state'];
if (!state) {
throw new Error('Invalid request, an initial state could not be found');
}
It appears that after the back button click, a0:state cookie isn’t available, and redirecting the user to /api/login endpoint doesn’t create a new one. At this point, I’m not sure why it isn’t created. Can you reproduce the same issue with the sample app link I shared earlier?
As a side note, I found an open issue in the project’s repository. Your issue is likely different than the ones reported there though.
The way I have this solved currently is I am catching that error inside callback and then redirecting them to the /api/login route
This looks like a good workaround solution in my opinion.