How to use sessions

Stytch user sessions are identified by a session token that should be stored client-side (usually a browser cookie) and authenticated on each request. To start a session, use the authenticate magic link or authenticate OTP endpoint as usual and add the session_duration_minutes parameter to set the lifetime of the session. The responses of these endpoints will include a session_token and session_jwt that you can forward to the client and store. Before performing any action that requires authorization, call authenticate session to ensure that the session is still valid.

Beginning a session

When handling the token for a new authentication factor (authenticate magic link or authenticate OTP), include a session_duration_minutes field to begin a new session. Sessions can be between 5 minutes and 366 days long (527040 minutes). If you provide this field, the authenticate method’s response field will include values for session, session_token, and session_jwt.

Authenticating a session

On each request, before doing anything that requires authorization, call authenticate session to ensure that the session is valid. If it is, use the user_id value to identify the user and send the session_token value to the user in a session cookie. If it isn’t valid, clear the session cookie to log the user out and do not process the request. sessions.authenticate always returns the session token for convenience. We recommend following OWASP's guide on cookie storage.

Extending or revoking a session

To extend a session’s lifetime, call authenticate session with the session_duration_minutes parameter. The session will be set to expire that many minutes from now. This will still return the original session token even though its lifetime was extended. To revoke a session, call revoke session with the session ID or session token (whichever is more convenient). We recommend showing the user a list of all their active sessions so they can revoke any they don’t recognize by IP address and/or User-Agent. To attach those values to sessions, add them to the attributes parameter in calls to authenticate magic link or [authenticate OTP](/docs/api/authenticate-otp.