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.handlerat/api/v1/authto handle sign-in and sign-up.
- Call auth.api.getSessioninside middleware to attachuserto the Hono context.
- Protect sensitive endpoints with a requireAuthmiddleware.
- Support API keys by enabling the apiKeyplugin in theauthconfiguration.
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.