Developing Locally with Cookie-Based Tokens
When testing in your local environment, you may encounter a 401 Unauthorized
error when trying to authenticate if you're storing your session tokens in cookies.
This issue arises because cookies are tied to your configured custom domain or api.descope.com
and are not sent in requests made from a different origin like localhost
. When your Descope settings are set to manage the session token in cookies, the cookie is set from the backend as http-only
. As a workaround, you can use our SDK to set the cookie from the client-side instead.
This guide provides steps to test cookies in a local development environment. It's generally recommended to create a separate Descope project for local development and testing, so these cookie settings will not impact your production environment.
Configure Descope Project
To test locally, adjust the Cookie Policy settings in your Descope Project Settings to ensure proper functionality on localhost
.
1. Manage the Refresh Token in either response body or cookies:
- If you choose to manage the refresh token in cookies and you have a configured custom domain, make sure the cookie policy is set to
None
.
The None
policy explicitly allows cookies to be sent in cross-origin requests, which is necessary when running your application on localhost
while the cookies are tied to your custom domain.
2. Store the session token in the response body:
- For the Session Token, select "Manage in response body".
Ensure you Save these changes.
3. Use the SDK flag:
When using either a custom domain or api.descope.com
, Descope returns the authentication response to the client with a Set-Cookie
response header. Since localhost
is not part of that cookie domain, the session token cannot be set this way when developing locally.
A workaround is available if you're using one of Descope's frontend SDKs. The SDK reads the server response and sets a cookie on the localhost
domain to mimic the regular cookie setup with Descope. This is done using the sessionTokenViaCookie
parameter on each SDK:
In the Next.js SDK, sessionTokenViaCookie
is automatically set to true
.
Passing Cookies To the Backend
To send the authentication cookies from the browser to your backend, configure your HTTP client to include credentials.
For example, with axios
set withCredentials: true
, or with fetch
use credentials: 'include'
.
For your backend, you must make sure your CORS settings explicitly allow credentials and specify your app's origin.
With each request, you can read the session cookie sent from the client, and validate the session using our session validation functions in our backend SDKs to authenticate the user.