Skip to content
Visual explainer 5h to learn 5 steps

Auth & a database

Add sign-in and persist user data to a hosted database.

By Invicly Tech, , in Frontend with React & Next.js. About 10 minutes to read.

Topic 26 of 36

In short

Most apps need users to sign in and data saved per user. An auth library handles sign-in and sessions, a hosted database stores data, and every page and action checks who the user is.

Explained simply

Many apps need accounts: each user signs in and sees only their own data, like their habits or recipes. Two parts make this work. Authentication proves who someone is. Authorization decides what that person is allowed to see and change.

Do not build sign-in from scratch. Passwords, sessions and security are easy to get wrong. Use a maintained auth library or service. Many apps offer Sign in with GitHub or Google, so the user never creates another password.

After sign-in, the server gives the browser a session cookie. On every request, your server reads that cookie to know who is calling. This is the only trustworthy source of the user's id.

The data lives in a hosted database, often PostgreSQL from a provider like Neon or Supabase. Every row that belongs to someone stores their userId, and every query filters by it, so people can never see each other's data.

Press Play on a diagram to walk through it one step at a time.

SequenceSign in, then save user data
User
Next.js app
Auth provider
Database
  1. 1Click Sign in
    User to Next.js app: Click Sign in
  2. 2Redirect to provider
    Next.js app to Auth provider: Redirect to provider
  3. 3Callback with verified identity
    Auth provider to Next.js app: Callback with verified identity
  4. 4Set secure session cookie
    Next.js app to User: Set secure session cookie
  5. 5Submit new habit
    User to Next.js app: Submit new habit
  6. 6Insert with userId from session
    Next.js app to Database: Insert with userId from session
SequenceLoading /habits for a signed-in user
Browser
Server component
Data access layer
Database
  1. 1GET /habits with session cookie
    Browser to Server component: GET /habits with session cookie
  2. 2getMyHabits()
    Server component to Data access layer: getMyHabits()
  3. 3verify session: user 12
    Data access layer to Data access layer: verify session: user 12
  4. 4SELECT ... WHERE user_id = 12
    Data access layer to Database: SELECT ... WHERE user_id = 12
  5. 5only user 12's rows
    Database to Data access layer: only user 12's rows
  6. 6HTML with their habits
    Server component to Browser: HTML with their habits

In depth

Choosing an auth approach

There are two broad options. Hosted services, such as Clerk or Supabase Auth, give you sign-in pages, user management and security features, and you pay as you grow. Libraries you run in your app, such as Auth.js or Better Auth, store users in your own database and are free, but you configure more yourself.

Whatever you choose, check four things: it supports the App Router and server components, it can read the session on the server in actions and route handlers, it supports the providers you need (OAuth with GitHub or Google, email magic links, passkeys), and it is actively maintained. OAuth means the user signs in on the provider's site, and the provider sends your app a verified identity, so you never handle their password.

  • Hosted: Clerk, Supabase Auth and others
  • Self-run libraries: Auth.js, Better Auth
  • OAuth providers: GitHub, Google
  • Check server-side session access in actions

Sessions and cookies

After sign-in the app must remember the user. There are two common designs. A database session stores a random session id in a cookie and the details in a sessions table, so you can sign a user out everywhere by deleting rows. A JWT session stores signed (and often encrypted) user data in the cookie itself, so no database lookup is needed, but revoking it before it expires is harder.

Either way, the cookie should be HttpOnly so JavaScript cannot read it, Secure so it only travels over HTTPS, and SameSite=Lax, which blocks most cross-site request forgery. Keep the signing secret, such as AUTH_SECRET, in environment variables and rotate it if it leaks. Expire sessions after a sensible time, and renew them while the user is active.

CompareDatabase session vs JWT session
Database session
  • Cookie holds a random id
  • Lookup on each request
  • Easy to revoke instantly
  • Needs a sessions table
JWT session
  • Cookie holds signed user data
  • No lookup needed
  • Hard to revoke before expiry
  • Keep the payload small

Connecting a hosted database

Create a Postgres database at a host, copy its connection string into DATABASE_URL in .env.local for development and into your hosting provider's environment settings for production. Never prefix it with NEXT_PUBLIC_, which would ship it to browsers.

Serverless platforms start many short-lived function instances, and each opening its own database connection can exhaust the database's connection limit. Use the provider's pooled connection string (a connection pooler such as PgBouncer sits in front of Postgres) or a serverless driver that talks over HTTP or WebSockets, such as Neon's. An ORM or query builder like Drizzle or Prisma gives you typed queries and migrations; run migrations as a deploy step, not when the app starts.

Authorization on every path

Hiding a Delete button does not protect anything. Every server component that reads private data, every server action and every route handler must check the session itself. The cleanest way is a small data access layer: server-only functions like getHabitsForCurrentUser() and deleteHabit(id) that read the session, return nothing or throw when it is missing, and always include userId in the query.

Watch for IDOR (insecure direct object reference): an action deleteHabit(id) that deletes by id alone lets anyone delete any habit by guessing ids. Always filter by both: where id = $1 and user_id = $2. If nothing matches, treat it as not found. Pages can redirect signed-out users with redirect("/login") from next/navigation.

LayersWhere checks live in a Next.js app
  1. 1
    Proxy

    Optional fast redirect when no session cookie

  2. 2
    Pages, actions, route handlers

    Call the data access layer only

  3. 3
    Data access layer

    Verify session, check ownership

  4. 4
    Database

    Every query filtered by user_id

Learn it in 5 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Choose an auth library and provider~1h
  2. 2
    Add sign-in and sign-out~1h
  3. 3
    Connect to a hosted database~1h
  4. 4
    Persist user data per account~1h
  5. 5
    Protect pages and actions by user~1h

Key points

  • Use a maintained auth library or service instead of writing your own crypto.
  • Always take the user ID from the server session, never from the request body.
  • Filter every query by the current user so people only see their own data.
  • Keep database credentials in server-only environment variables.

Key terms

Tap a card to flip it. 0/5 known

Examples

ts
'use server';
import { revalidatePath } from 'next/cache';

export async function addHabit(formData: FormData) {
  const session = await getSession(); // from your auth library
  if (!session) throw new Error('Not signed in');

  const name = String(formData.get('name') ?? '').trim();
  if (!name) return;

  await db.habit.create({ data: { name, userId: session.user.id } });
  revalidatePath('/habits');
}

The user ID always comes from the session.

GitHub sign-in with Auth.js v5

Step 1: create a GitHub OAuth app with the callback URL /api/auth/callback/github. Step 2: set AUTH_SECRET, AUTH_GITHUB_ID and AUTH_GITHUB_SECRET as environment variables. Step 3: configure NextAuth once in auth.ts, which exports handlers, auth, signIn and signOut. Step 4: mount the handlers in a catch-all route. Step 5: any server component or action can now call await auth() to get the session.

ts
// auth.ts
import NextAuth from "next-auth";
import GitHub from "next-auth/providers/github";

export const { handlers, auth, signIn, signOut } = NextAuth({
  providers: [GitHub],
});

// app/api/auth/[...nextauth]/route.ts
import { handlers } from "@/auth";
export const { GET, POST } = handlers;

// in a server component or action:
// const session = await auth();
// if (!session?.user) redirect("/login");

A per-user habits table with Drizzle

Step 1: define the table with a user_id column and an index on it. Step 2: create the db client from DATABASE_URL using the Neon HTTP driver, which suits serverless. Step 3: every query filters by the current user's id. Step 4: delete uses both id and userId, so guessing another habit's id does nothing.

ts
import { pgTable, serial, text, timestamp, index } from "drizzle-orm/pg-core";
import { drizzle } from "drizzle-orm/neon-http";
import { and, eq } from "drizzle-orm";

export const habits = pgTable("habits", {
  id: serial("id").primaryKey(),
  userId: text("user_id").notNull(),
  name: text("name").notNull(),
  createdAt: timestamp("created_at").defaultNow().notNull(),
}, (t) => [index("habits_user_idx").on(t.userId)]);

export const db = drizzle(process.env.DATABASE_URL!);

export const listHabits = (userId: string) => db.select().from(habits).where(eq(habits.userId, userId));
export const removeHabit = (id: number, userId: string) =>
  db.delete(habits).where(and(eq(habits.id, id), eq(habits.userId, userId)));

Quick reference

  • Authentication: who you are. Authorization: what you may do
  • Use a maintained auth library or service; never hand-roll password storage
  • Session cookies: HttpOnly, Secure, SameSite=Lax
  • Always take userId from the server session, never from the request
  • Filter every read and write by user_id to prevent IDOR bugs
  • Database URLs are server-only: never prefix them with NEXT_PUBLIC_
  • On serverless, use a pooled connection string or an HTTP/WebSocket driver
  • Put session checks in a server-only data access layer that everything calls

Common mistakes

  • Hiding a button in the UI but not checking permissions on the server.
  • Trusting a userId sent from the client.
  • Exposing database secrets with a NEXT_PUBLIC_ prefix.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1deleteHabit(id) runs DELETE FROM habits WHERE id = $1 after checking the user is signed in. What is wrong?

Question 2

2Which cookie flag stops JavaScript in the page from reading the session cookie?

Question 3

3Your serverless app hits too many connections errors on Postgres under load. What is the usual fix?

Question 4

4What is a downside of JWT sessions compared with database sessions?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Protect the /habits page so signed-out visitors are sent to /login.

  2. Exercise 2medium

    Write a server-only data access function getMyHabits() that returns the current user's habits, or throws if nobody is signed in.

  3. Exercise 3hard

    Write a server action renameHabit(formData) that validates id (number) and name (1 to 50 chars) with Zod, updates only the current user's habit, returns an error if nothing matched, and revalidates /habits.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Which auth library should I use with Next.js?
Pick a maintained option that supports the App Router and server-side session access, such as Auth.js, Better Auth, Clerk or Supabase Auth. Hosted services save setup time; self-run libraries keep users in your own database.
Is it safe to check auth only in middleware or proxy?
No. Use it for fast redirects, but check the session again in every page, server action and route handler that touches private data.
Where should I store the database password?
In server-only environment variables: .env.local for development (not committed) and your host's settings for production.

Go deeper

ShareXLinkedInWhatsApp