theAuth: Add Login to an Existing Next.js App A developer published a step-by-step guide for adding username/password login, cookie sessions, and protected pages to an existing Next.js App Router application using theAuth, an open-source TypeScript auth library that also handles AI agent identity. The walkthrough covers installing @glinr/theauth, configuring a session secret, creating shared instances and session managers, adding sign-up/sign-in/sign-out route handlers, and guarding pages with middleware, totaling roughly 150 lines across six or seven files. theAuth is open-source auth for AI agents and humans. Star the repo on GitHub https://github.com/glincker/theauth · Read the docs https://docs.theauth.dev?utm source=devto&utm medium=article&utm campaign=guide-1-add-auth-existing-nextjs-app-typescript · Run the quickstart https://docs.theauth.dev/quickstart?utm source=devto&utm medium=article&utm campaign=guide-1-add-auth-existing-nextjs-app-typescript · theauth.dev https://theauth.dev?utm source=devto&utm medium=article&utm campaign=guide-1-add-auth-existing-nextjs-app-typescript Last month I opened a side project I had shipped with no login at all. Every page was public, every API route trusted whoever called it. I had told myself I would "add auth later," and later arrived the day a friend pasted my admin URL into a group chat. Adding auth to a running app is a different job from starting a new one. You have routes, layouts, and data that already exist. You cannot scaffold your way out of it. You need a small, boring set of changes that you can read in one sitting and undo if they go wrong. This guide walks that path with theAuth, an open-source TypeScript auth library that also handles AI agent identity. We will add username and password login, cookie sessions, and protected pages to a Next.js App Router app. I wrote it from the docs and the package source, so every import and option below exists in the code. Where a feature is missing or rough, I say so. This is guide 1 of 8 in the theAuth guides. It stands on its own, so you can start right here. Nothing comes before it. If you build for AI agents rather than people, jump to guide 5. | Guide | Title | Read it when | |---|---|---| | 1 | Add login to an existing Next.js app this guide | You have an app with no auth yet | | 2 | Passwordless login: passkeys, links, OTP https://dev.to/thegdsks/passwordless-login-in-typescript-passkeys-links-otp-59ja | You want to drop passwords or add 2FA | | 3 | Multi-tenant SaaS auth: orgs, RBAC, SSO, SCIM https://dev.to/thegdsks/multi-tenant-saas-auth-orgs-rbac-sso-and-scim-1fod | You sell to teams and companies | | 4 | Migrate from Auth0 or Clerk https://dev.to/thegdsks/migrate-from-auth0-or-clerk-to-theauth-step-by-step-4o47 | You already run another provider | | 5 | Give every AI agent its own identity https://dev.to/thegdsks/give-every-ai-agent-its-own-identity-and-permissions-49mf | You run AI agents and need to start somewhere | | 6 | Cap agent spend and require human approval https://dev.to/thegdsks/cap-agent-spend-and-require-human-approval-in-typescript-2k9h | Your agents spend money or act on risky things | | 7 | Secure an MCP server for production https://dev.to/thegdsks/securing-an-mcp-server-for-production-step-by-step-53h7 | You expose tools over MCP | | 8 | Build an audit trail for AI agent actions https://dev.to/thegdsks/build-an-audit-trail-for-ai-agent-actions-23j7 | Someone will ask what your agents did | Building for people? Start at guide 1. Building for AI agents? Start at guide 5. Every guide links to the docs page for each concept it touches. | Step | What you do | Where | |---|---|---| | 1 | Install @glinr/theauth | terminal | | 2 | Add a 32+ character session secret | .env.local | | 3 | Create one shared instance and session manager | lib/theauth.ts | | 4 | Add sign-up, sign-in, and sign-out route handlers | app/api/account/ | | 5 | Read the session in server code | lib/auth.ts | | 6 | Guard pages with middleware plus a server check | middleware.ts , app/dashboard | | 7 | Build the forms and run the first login | app/sign-in , app/sign-up | Expect about 150 lines of code in total. You will touch six or seven files and add zero new database tables by hand. You need an existing Next.js app on the App Router. The @glinr/theauth-nextjs adapter declares next = 14 as its peer dependency. The code in this guide uses the async headers function from Next.js 15, so on 14 you drop the await . You need Node.js 18 or later and a package manager. I use pnpm. The commands translate to npm or yarn without changes. You need a database. SQLite works for local development and needs no setup. For production, plan on Postgres or MySQL, or D1 on Cloudflare . theAuth creates its own tables with a theauth prefix next to yours, so it does not touch your schema. One honest note before you invest an hour. theAuth takes an agent-first approach to design. Its built-in human sign-in is username and password, not email and password, and it ships headless: no prebuilt login page, no social buttons wired by default. If you want email sign-in with a hosted UI in ten minutes, Clerk or Auth.js will get you there faster. If you want one library that also issues identities to your AI agents later, keep reading. I cover this tradeoff again near the end. pnpm add @glinr/theauth That one package carries the core, the SQLite driver sql.js , compiled to WebAssembly , the username module, and the session managers. For Postgres, add the pg driver as well: pnpm add pg pnpm add -D @types/pg The database driver is an optional peer dependency, so theAuth only loads it when you pick that provider. If you forget it, you get a clear startup error that names the missing package. The database setup page https://docs.theauth.dev/database lists the driver for each provider, including the native SQLite option that needs a C++ build step. You do not need @glinr/theauth-nextjs yet. That adapter mounts agent and MCP endpoints, not human login. I come back to it in step 8. Generate a session secret and put it in .env.local : openssl rand -base64 32 .env.local SESSION SECRET=paste-the-generated-value-here APP HOST=localhost:3000 Production only: your public host name and database APP HOST=app.example.com DATABASE URL=postgresql://user:password@host:5432/dbname The secret signs every session token, and theAuth rejects anything under 32 characters. Keep this value stable across deploys. A new secret invalidates every cookie already out there, which signs all your users out at once. The cookie options page https://docs.theauth.dev/cookies says plainly that theAuth does not support a list of secrets for rotation, so plan any change for a quiet hour. Create two files. The first holds the cookie name and the app origin in a short module, so the middleware can import them later without pulling in a database driver. The second, lib/theauth.ts , builds the theAuth instance and the cookie session manager once per process. js // lib/constants.ts export const SESSION COOKIE = 'theauth session'; const scheme = process.env.NODE ENV === 'production' ? 'https' : 'http'; export const BASE URL = ${scheme}://${process.env.APP HOST ?? 'localhost:3000'} ; js // lib/theauth.ts import { createCookieSessionManager, createTheAuth } from '@glinr/theauth'; import { BASE URL, SESSION COOKIE } from './constants'; const isProd = process.env.NODE ENV === 'production'; async function init { const theauth = await createTheAuth { database: isProd ? { provider: 'postgres', url: process.env.DATABASE URL } : { provider: 'sqlite', url: './theauth-dev.db' }, baseUrl: BASE URL, auth: { session: { secret: process.env.SESSION SECRET , cookieName: SESSION COOKIE }, }, username: {}, } ; if theauth.username { throw new Error 'The username module did not start. Check auth.session.' ; } const sessions = createCookieSessionManager { secret: process.env.SESSION SECRET , sessionName: SESSION COOKIE, maxAge: 7 24 60 60, autoRefresh: false, cookieOptions: { httpOnly: true, secure: isProd, sameSite: 'lax', path: '/' }, }, theauth.db, ; return { theauth, username: theauth.username, sessions }; } type TheAuthContext = Awaited