Authentication JWT access and refresh tokens with Effect

Languages

typescript5.6.3

Libraries

effect3.10.12
nodejs22.8.6
next15.0.2
GithubCode

When implementing authentication using a JWT (JSON Web Token) the frontend stores 2 information:

  • Access token (JWT)
  • Refresh token

A JWT token encodes information about the user and some other metadata. One of these metadata is the expiration date (exp). When the token expires, the frontend must request a new one using the refresh token.

This script implements a CookieToken service in effect that handles the JWT token and refresh token.

CookieToken depends on two other separate services:

  • Jwt: decodes JWT token and exposes isExpired method
  • Cookies: reads and writes cookies

Jwt uses the jwt-decode library to decode the token and extract the expiration date.

Every time you access the token using the get method from CookieToken, the service checks if the token is expired. If it is, it requests a new one using the refresh token.

The snippet implements a generic Cookies service to get, set and remove cookies.

The code includes an example of how to integrate CookieToken with next. It adds a NextCookies layer inside Cookies that implements cookies from next/headers.