Skip to content

Auth Middleware ​

A middleware that checks a bearer token, hands the user to the handlers after it through event.store, and answers 401 otherwise. A route registered before the middleware stays public.

ts
import { App, AppError, defineCoreHandler } from 'routup';

type User = {
    name: string,
};

const TOKEN = 'secret-token';
const USER = Symbol('user');

export const app = new App();

app.get('/health', defineCoreHandler(() => ({ status: 'ok' })));

app.use(defineCoreHandler((event) => {
    if (event.headers.get('authorization') !== `Bearer ${TOKEN}`) {
        throw new AppError({ status: 401, message: 'Unauthorized' });
    }

    event.store[USER] = { name: 'Alice' } satisfies User;

    return event.next();
}));

app.get('/me', defineCoreHandler((event) => {
    const user = event.store[USER] as User;

    return { name: user.name };
}));

Try It ​

Install routup, serve the app from a second file and start it with your runtime as on the Quickstart:

typescript
import { serve } from 'routup';
import { app } from './app.ts';

serve(app, { port: 3000 });
bash
curl http://localhost:3000/health
# {"status":"ok"}

curl http://localhost:3000/me
# {"status":401,"message":"Unauthorized"}

curl http://localhost:3000/me -H 'authorization: Bearer wrong'
# {"status":401,"message":"Unauthorized"}

curl http://localhost:3000/me -H 'authorization: Bearer secret-token'
# {"name":"Alice"}

How It Works ​

  • Handlers run in registration order. /health answers before the middleware is reached, so it needs no token. See Registration order.
  • app.use(handler) without a path runs the middleware for every request that gets to it; event.next() continues with the handlers after it. An unknown path without a valid token therefore answers 401, not 404. See Global.
  • The token is a constant to keep the example short. A real app verifies it with its auth library, or compares it in constant time.
  • event.store lives for one request and is shared by all its handlers. A Symbol key cannot collide with keys of other middleware or plugins. See Data Sharing.
  • The 401 AppError reaches no error handler, so it becomes the fallback response with status 401.