๐ง Example Code
import { Server, json, setCookie, requireAuth } from "tirne";
import type { Route } from "tirne";
const routes: Route[] = [
{
method: "GET",
path: "/login",
handler: () => {
const headers = new Headers();
headers.append("Set-Cookie", setCookie("auth", "valid-token", {
httpOnly: true,
path: "/",
maxAge: 3600,
}));
return json({ message: "Logged in" }, 200, headers);
},
middleware: [], // No auth middleware on /login
},
{
method: "GET",
path: "/private",
handler: () => json({ message: "Secret data only for authenticated users" }),
middleware: [requireAuth], // Protect /private
},
];
const server = new Server(routes);
export default {
fetch: (req: Request) => server.fetch(req),
};
๐งช How to Test
Try these curl commands to verify cookie-based behavior:
1. ๐ Access /login
(No Auth Required)
curl -i http://localhost:3000/login
HTTP/1.1 200 OK
Content-Type: application/json
Set-Cookie: auth=valid-token; Path=/; HttpOnly; Max-Age=3600
{"message":"Logged in"}
2. ๐ Access /private
(With Cookie)
curl -i --cookie "auth=valid-token" http://localhost:3000/private
{"message":"Secret data only for authenticated users"}
3. โ Access /private
(No Cookie)
curl -i http://localhost:3000/private
{"error":"unauthorized","message":"Unauthorized"}