Skip to content

PostgREST JWT Authentication

Beau Barker edited this page Nov 5, 2025 · 32 revisions

This allows you to authenticate to Postgrest using a JWT token in the Authorization header:

Authorization: Bearer eyJhbGciOiJIUzI1...

Create a JWT Secret

Note

PostgREST can share the JWT secret with Caddy.

Generate a secret:

openssl rand -base64 32

PostgREST

Put the secret in the environment file:

app/.env

JWT_SECRET=(your secret)

Add the secret to the PostgREST service:

postgrest:
  environment:
    PGRST_JWT_SECRET: ${JWT_SECRET:?}
    PGRST_JWT_SECRET_IS_BASE64: true
    PGRST_APP_SETTINGS_JWT_EXP: 3600 # Recommended - the default is no expiry!

Postgres

The secret is needed in the Postgres service because a migration will configure PostgREST:

db/.env

JWT_SECRET=(your secret)

db/compose.yaml

postgres:
  environment:
    JWT_SECRET: ${JWT_SECRET:?}

Add a migration to configure PostgREST:

db/postgres/migrations/02-auth_schema.sql

\set pgrst_jwt_secret '$JWT_SECRET'

-- Set the JWT secret in the db - despite it being set in the JWT_SECRET
-- env var, this appears to be also required
alter system set pgrst.jwt_secret = :'pgrst_jwt_secret';

Caddy

Split your Caddyfile into public and JWT-protected sections. The private routes require a valid access token:

app/caddy/Caddyfile

{$CADDY_SITE_ADDRESS}

# --- Public routes ---

# PostgREST's OpenAPI endpoint
handle_path /rest/ {
  reverse_proxy http://postgrest:3000
}

# --- JWT protected routes ---

route {

  # Set the Authorization header from the Cookie header
  # Only if it's not already set
  @noHeader not header Authorization *
  request_header Authorization "Bearer {cookie.access_token}" # fallback to cookie

  handle /rpc/* {
    reverse_proxy http://postgrest:3000
  }

  handle_path /rest/* {
    reverse_proxy http://postgrest:3000
  }

  # .. Other authenticated endpoints ..

}

Restart Caddy for the changes to take effect:

docker compose up -d --force-recreate caddy

Clone this wiki locally