"Missing State Cookie From Login Request" Error in Custom Next.js Invitation Flow
A custom invitation flow is implemented in a Next.js application by creating a custom login route. This route accepts invitation and organization parameters to construct an authorize URL, similar to:
https://{customer domain}/authorize?client_id=${process.env.NEXT_PUBLIC_AUTH0_CLIENT_ID}&invitation=${invitation}&organization=${organization}&redirect_uri={callback url}&response_type=code
The accept invitation and registration flows work correctly. However, after a successful authorization, the application redirects to the callback page (e.g., https://{callback_url}?code=<value>) and throws an error:
[CallbackHandlerError]: Callback handler failed. CAUSE: Missing state cookie from login request (check login URL, callback URL and cookie config).
The manually constructed /authorize URL does not include a value for the state parameter. The application uses nextjs-auth0 version 3.5.0.
This article clarifies why this error occurs and provides the correct method for implementing an organization invitation flow.
-
Next.js
-
Custom
/authorizeURL -
Callback Page
Using the SDK's login handler (e.g., /api/auth/login) is essential, as it sets the state cookie. This cookie is required and subsequently checked during the /api/auth/callback API call.
The issue occurs because the custom flow bypasses the SDK's /api/auth/login handler and calls the /authorize endpoint directly. This prevents the state cookie from being set, which causes the callback API call to fail.
To set the cookies correctly, the /api/auth/login endpoint must be visited in the browser (as a document request), which then redirects to /api/auth/callback to read them.
The state parameter is required in the /authorize URL for successful user authorization.
Directly calling the /authorize endpoint with manually added parameters is not the recommended approach, as it is prone to misconfiguration. The ideal approach is to utilize the SDK's configuration to implement a customized organization invitation flow.
-
The Next.js SDK supports configuring the organization invitation flow.
-
Use the
AuthorizationParamsinterface within the login handler to configure the organization and invitation properties in the SDK.
import { handleAuth, handleLogin } from '@auth0/nextjs-auth0';
export const GET = handleAuth({
login: async (req, res) => {
try {
return await handleLogin(req, res, {
authorizationParams: { organization: '<org_id>', invitation: '<invitation>'}
});
} catch (error) {
console.error(error);
}
}
});
- When the
/api/auth/loginURL is accessed, the SDK automatically builds the correct/authorizeURL with all required properties, including thestateparameter.