๐Ÿ” Auth Middleware

Token Validation via Cookie or Header

This example shows how to protect routes using a custom createAuth() middleware. After logging in via /login, the server sets a JWT token as a cookie. You can also send the token manually using an Authorization header.

Token-based auth with cookie fallback โ€” secure, flexible, and extensible.

๐Ÿ”ง Example Code

import type { Route } from "tirne";
import { Server,createAuth,json,generateToken,setCookie } from "tirne";


const SECRET = "super-secret-key";

const routes: Route[] = [
  {
    method: "POST",
    path: "/login",
    handler: async (req) => {
      const token = await generateToken({
        id: "user123",
        role: "admin",
        iat: Date.now(),
        jti: crypto.randomUUID(),
      }, SECRET);
      const headers = new Headers();
      headers.set("Set-Cookie", setCookie("auth", token, {
        httpOnly: true,
        path: "/",
        maxAge: 3600,
      }));
      return json({ token }, 200, headers);
    },
  },
  {
    method: "GET",
    path: "/me",
    handler: (req) => {
      const user = (req as any).user;
      return json({ user });
    },
    middleware: [createAuth({ secret: SECRET })],
  },
];

const server = new Server(routes);

export default {
  fetch: (req: Request) => server.fetch(req),
};

๐Ÿงช How to Test Authentication

Try the following steps to validate token-based authentication:

1. ๐Ÿ” Log in and Get Token

curl -X POST http://localhost:3000/login -i
HTTP/1.1 200 OK
Set-Cookie: auth=eyJpZCI6...; HttpOnly

2. โœ… Access /me with Cookie

curl --cookie "auth=<your-token-here>" http://localhost:3000/me
{
  "user": {
    "id": "user123",
    "role": "admin"
  }
}

3. โœ… Access /me with Authorization Header

curl -H "Authorization: Bearer <your-token-here>" http://localhost:3000/me

4. โŒ Access /me without Token

curl http://localhost:3000/me
{
  "error": "unauthorized",
  "message": "Unauthorized"
}