How to clear an expired session cookie from the auth gateway in Encore.ts

1 day ago 3
ARTICLE AD BOX

You cannot modify the HTTP response (including setting cookies) from the auth handler itself - the auth handler only returns auth data or throws an error. However, you can achieve this using middleware.

Create a middleware that runs after the endpoint handler and checks whether the request was authenticated. If getAuthData() returns null, set a Set-Cookie header that expires the session cookie:

import { middleware } from "encore.dev/api"; import { getAuthData } from "~encore/auth"; export const clearSessionCookie = middleware(async (req, next) => { const resp = await next(req); const authData = getAuthData(); if (authData === null) { resp.header.set( "Set-Cookie", "session=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax", ); } return resp; });

This middleware will run for endpoints that do not have auth: true set (since unauthenticated requests can still reach those endpoints). For endpoints that require authentication, handle session renewal or logout on the client side - for example, by calling a dedicated logout endpoint.

Register the middleware in your service definition:

import { Service } from "encore.dev/service"; export default new Service("myService", { middlewares: [clearSessionCookie], });

Relevant docs:

Encore.ts Middleware

Encore.ts Authentication

Encore.ts Cookies

Read Entire Article