Browse docs

Express quickstart

authfyio-backend is framework-agnostic. It works with Express, Fastify, Hono, Koa, NestJS, or a bare Node http server — anywhere you have access to the incoming cookie header.

Copy this quickstart guide as a prompt for LLMs to implement Authfyio in your application.

1. Install

npm install authfyio-backend

2. Build a client

src/authfyio.ts
import { AuthfyioBackendClient } from 'authfyio-backend';

export const kolay = new AuthfyioBackendClient({
  // baseUrl defaults to https://api.authfyio.com
  issuer: process.env.AF_JWT_ISSUER,
});

3. Protect an Express route

src/server.ts
import express from 'express';
import { kolay } from './authfyio';

const app = express();

app.get('/api/me', async (req, res) => {
  const claims = await kolay.getSessionFromRequest(req).catch(() => null);
  if (!claims) return res.status(401).json({ error: 'unauthorized' });
  res.json({ userId: claims.sub, orgId: claims.org ?? null });
});

app.listen(4000);

Fastify

import Fastify from 'fastify';
import cookie from '@fastify/cookie';
import { kolay } from './authfyio';

const app = Fastify();
await app.register(cookie);

app.get('/api/me', async (req, reply) => {
  const claims = await kolay.getSessionFromRequest({
    headers: { cookie: req.headers.cookie ?? '' },
  }).catch(() => null);
  if (!claims) return reply.code(401).send({ error: 'unauthorized' });
  return { userId: claims.sub };
});

Hono

import { Hono } from 'hono';
import { kolay } from './authfyio';

const app = new Hono();
app.get('/api/me', async (c) => {
  const cookie = c.req.header('cookie') ?? '';
  const claims = await kolay.getSessionFromRequest({ headers: { cookie } }).catch(() => null);
  if (!claims) return c.json({ error: 'unauthorized' }, 401);
  return c.json({ userId: claims.sub });
});
export default app;

Verify a raw token

If your proxy strips cookies and forwards an Authorization: Bearer header instead, verify the JWT directly with verifySessionJwt.

import { verifySessionJwt } from 'authfyio-backend';

const claims = await verifySessionJwt(token, {
  jwksUrl: "https://api.authfyio.com" + '/.well-known/jwks.json',
  issuer: process.env.AF_JWT_ISSUER,
});