API Authentication Usage

Using Authentication in the API

This guide demonstrates how to apply @repo/auth inside the Hono based API server.

Middleware

import { Hono } from "hono"; import { auth } from "@repo/auth"; const app = new Hono(); app.use("/api/*", async (c, next) => { const session = await auth.api.getSession({ headers: c.req.raw.headers }); if (session) c.set("user", session.user); await next(); });

Use auth.api.getSession to read the session from incoming requests and attach the user to the context. You can then create helpers like requireAuth to protect routes.

import { HTTPException } from "hono/http-exception"; const requireAuth = async (c: Context, next: Next) => { const user = c.get("user"); if (!user) throw new HTTPException(401); await next(); };

Common flows

  • Mount auth.handler at /api/v1/auth to handle sign-in and sign-up.
  • Call auth.api.getSession inside middleware to attach user to the Hono context.
  • Protect sensitive endpoints with a requireAuth middleware.
  • Support API keys by enabling the apiKey plugin in the auth configuration.

Example protected route

router.get("/projects", requireAuth, async (c) => { const user = c.get("user"); const projects = await getUserProjects({ userId: user.id }); return c.json(projects); });

Refer back to Authentication for more details.