Next.js / 17 min read

How I Built Authentication in Next.js Without NextAuth

Build authentication in Next.js with Supabase SSR, including cookie-based sessions, login, signup, token refresh, protected routes, and secure access checks.

No reproducible test record has been approved for this published version. Check its commands against your software versions before using them.

How we verify guides
How I Built Authentication in Next.js Without NextAuth
On this page

Table of Contents

Next.js Authentication with Supabase (Without NextAuth)

Authentication is one of those features that looks straightforward until you start connecting browser sessions, server-rendered pages, cookies, and protected database queries.

A login form may work perfectly in the browser while a Next.js Server Component behaves as though nobody is signed in.

Or the user can open a protected dashboard, but a server-side operation fails because it doesn't have the expected authentication context.

If you're already using Supabase for your database, you don't necessarily need NextAuth (now also known as Auth.js) to solve these problems.

Supabase Auth and @supabase/ssr provide a way to handle authentication directly in a Next.js App Router application.

In this tutorial, we'll cover:

  • Setting up Supabase Auth in Next.js
  • Creating separate browser and server clients
  • Managing authentication sessions with cookies
  • Refreshing sessions using Next.js Proxy
  • Building login and signup forms with Server Actions
  • Protecting pages, data, and server operations
  • Implementing logout
  • Understanding common authentication mistakes

The examples target Next.js 16 and the modern Supabase SSR approach.

Prerequisites: A Next.js App Router project, a Supabase project, and basic familiarity with TypeScript. The implementation below is an educational starting point; validate the entire authentication flow in a separate environment before production use.

1. Why Use Supabase Auth Instead of NextAuth?

NextAuth/Auth.js and Supabase Auth can both be reasonable choices.

They aren't interchangeable in every application.

Auth.js provides authentication integrations and session-management options for different application architectures.

Supabase Auth is particularly convenient when your application already uses Supabase PostgreSQL and Row Level Security.

For example, you might want to:

  • Authenticate users with email and password.
  • Manage sessions in a server-rendered Next.js application.
  • Identify authenticated users in PostgreSQL RLS policies.
  • Add OAuth providers later.
  • Keep authentication and database access within the same platform.

Using Supabase doesn't eliminate the need for secure authorization logic.

Authentication tells your application who a user is.

Authorization determines what that user is allowed to access.

We'll handle both concerns separately.

2. Understand How Supabase SSR Authentication Works

A typical Next.js application needs three pieces:

Browser client: Handles browser-side authentication and interactive features.

Server client: Reads request cookies so Server Components, Server Actions, and Route Handlers can access the user's session.

Proxy: Keeps authentication cookies synchronized when Supabase refreshes an expired or nearly expired access token.

A simplified authentication flow looks like this:

text
User submits login form
          |
          v
Next.js Server Action
          |
          v
Supabase Auth verifies credentials
          |
          v
Session cookies are written
          |
          v
Browser requests protected page
          |
          v
Next.js Proxy handles session refresh
          |
          v
Server verifies user identity
          |
          v
Database enforces RLS permissions

Cookies are particularly useful for server-rendered applications because they travel with HTTP requests.

Unlike browser local storage, request cookies can be accessed by server-side Next.js code.

However, receiving a cookie is not proof that its contents can be trusted.

The server must verify the authentication token before making protected decisions.

3. Install Supabase Packages

Inside your Next.js project, install the required packages:

bash
npm install @supabase/supabase-js @supabase/ssr

The @supabase/supabase-js package provides the Supabase client and authentication APIs.

The @supabase/ssr package provides helpers for cookie-based sessions in server-rendered applications.

Configure environment variables

Create a .env.local file in your project root:

env
NEXT_PUBLIC_SUPABASE_URL=https://your-project.supabase.co
NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=your-publishable-key

Replace the placeholders with the values from your Supabase project's dashboard.

The publishable key is intended for public application access when combined with properly configured database permissions and RLS.

Never place secret or service-role credentials in a NEXT_PUBLIC_ variable.

Also confirm your Supabase project's authentication settings, site URL, and permitted redirect URLs.

4. Organize Your Authentication Files

For a Next.js project using the src directory, use a structure like this:

text
src/
├── app/
│   ├── login/
│   │   └── page.tsx
│   ├── signup/
│   │   └── page.tsx
│   ├── dashboard/
│   │   └── page.tsx
│   └── auth/
│       └── confirm/
│           └── route.ts
│
├── features/
│   └── auth/
│       └── actions.ts
│
├── lib/
│   ├── auth/
│   │   └── require-user.ts
│   └── supabase/
│       ├── client.ts
│       ├── server.ts
│       └── proxy.ts
│
└── proxy.ts

The confirmation route is relevant when you use email confirmation links or password recovery flows.

We'll explain its role later.

The important distinction is that src/proxy.ts is the Next.js entry point, while src/lib/supabase/proxy.ts is an ordinary helper module.

5. Create the Supabase Browser Client

Create:

src/lib/supabase/client.ts

ts
import { createBrowserClient } from "@supabase/ssr";

export function createClient() {
  return createBrowserClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!
  );
}

Use this client inside browser-side Client Components.

For example, a Client Component may need to display session-related UI or subscribe to authorized realtime events.

The browser client must use public credentials rather than privileged server keys.

6. Create the Supabase Server Client

Create:

src/lib/supabase/server.ts

ts
import "server-only";

import { createServerClient } from "@supabase/ssr";
import { cookies } from "next/headers";

export async function createClient() {
  const cookieStore = await cookies();

  return createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll();
        },

        setAll(cookiesToSet) {
          try {
            cookiesToSet.forEach(
              ({ name, value, options }) => {
                cookieStore.set(name, value, options);
              }
            );
          } catch {
            // Server Components cannot write cookies.
            // Proxy handles session refresh.
          }
        },
      },
    }
  );
}

This client can be used in Server Components, Server Actions, and Route Handlers.

Why are the browser and server clients separate?

Browser code and server code have different capabilities.

Browser code can interact with the user's interface.

Server code can access request cookies and perform trusted application operations.

Separating these environments helps prevent accidental imports of server-only functionality into browser code.

Supabase Auth may update its authentication tokens.

The server-side client uses its cookie adapter to read and write those values in supported request contexts.

Server Components cannot write response cookies.

That's why we also need a request-level session-refresh mechanism.

7. Refresh Sessions with Next.js Proxy

In Next.js 16, the previous Middleware convention was renamed to Proxy.

Create:

src/lib/supabase/proxy.ts

ts
import { createServerClient } from "@supabase/ssr";
import { NextResponse, type NextRequest } from "next/server";

export async function updateSession(
  request: NextRequest
) {
  let response = NextResponse.next({
    request,
  });

  const supabase = createServerClient(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY!,
    {
      cookies: {
        getAll() {
          return request.cookies.getAll();
        },

        setAll(cookiesToSet) {
          cookiesToSet.forEach(({ name, value }) => {
            request.cookies.set(name, value);
          });

          response = NextResponse.next({
            request,
          });

          cookiesToSet.forEach(
            ({ name, value, options }) => {
              response.cookies.set(
                name,
                value,
                options
              );
            }
          );
        },
      },
    }
  );

  await supabase.auth.getClaims();

  return response;
}

The important behavior is that refreshed tokens are written to both the outgoing response and the request's cookie state.

This keeps the browser and server-side rendering path synchronized.

Implementation warning: This is a simplified refresh helper for ordinary requests. If your application customizes response headers, redirects, cookie security attributes, or caching, adapt the helper carefully and preserve those settings when creating the response. Refer to Supabase's maintained example for the exact version you deploy.

Connect the helper to Next.js

Create:

src/proxy.ts

ts
import type { NextRequest } from "next/server";

import { updateSession } from "@/lib/supabase/proxy";

export async function proxy(
  request: NextRequest
) {
  return updateSession(request);
}

export const config = {
  matcher: [
    "/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)",
  ],
};

The matcher excludes common static assets.

Make sure your matcher still covers application routes and operations that rely on Supabase session refresh.

What about Next.js 15 and earlier?

Those versions use middleware.ts and an exported middleware() function instead of the Next.js 16 proxy.ts convention.

Use the file convention supported by your installed Next.js version.

Is Proxy enough to protect a route?

No.

Proxy is responsible for session handling and can perform optional redirects.

It should not be your application's only security boundary.

Authentication and authorization must also be checked where protected data is accessed or modified.

8. Build a Login Server Action

Next.js Server Actions can process login forms without requiring you to create a separate API endpoint.

Create:

src/features/auth/actions.ts

ts
"use server";

import { createClient } from "@/lib/supabase/server";
import { redirect } from "next/navigation";

export type AuthFormState = {
  error: string | null;
};

export async function login(
  _previousState: AuthFormState,
  formData: FormData
): Promise<AuthFormState> {
  const email = formData.get("email");
  const password = formData.get("password");

  if (
    typeof email !== "string" ||
    typeof password !== "string" ||
    !email.trim() ||
    !password
  ) {
    return {
      error: "Enter your email and password.",
    };
  }

  const supabase = await createClient();

  const { error } =
    await supabase.auth.signInWithPassword({
      email: email.trim(),
      password,
    });

  if (error) {
    return {
      error: "Unable to sign in. Check your credentials.",
    };
  }

  redirect("/dashboard");
}

Notice that we validate the submitted values before calling Supabase.

We also return a safe error message rather than exposing raw internal authentication details.

The redirect happens after the authentication result is checked.

9. Create the Login Form

Create:

src/app/login/page.tsx

tsx
"use client";

import { useActionState } from "react";

import {
  login,
  type AuthFormState,
} from "@/features/auth/actions";

const initialState: AuthFormState = {
  error: null,
};

export default function LoginPage() {
  const [state, formAction, pending] =
    useActionState(login, initialState);

  return (
    <main>
      <h1>Sign in</h1>

      <form action={formAction}>
        <label htmlFor="email">Email</label>
        <input
          id="email"
          name="email"
          type="email"
          autoComplete="email"
          required
        />

        <label htmlFor="password">
          Password
        </label>
        <input
          id="password"
          name="password"
          type="password"
          autoComplete="current-password"
          required
        />

        {state.error && (
          <p role="alert">{state.error}</p>
        )}

        <button type="submit" disabled={pending}>
          {pending ? "Signing in..." : "Sign in"}
        </button>
      </form>
    </main>
  );
}

This is a minimal form that demonstrates the authentication flow.

A production interface may also need loading states, accessible styling, rate-limit messaging, account recovery, and other UX features.

Server Actions must validate their inputs and enforce their own authorization rules when performing protected operations.

10. Add User Signup

Supabase provides the signUp() method for email/password registration.

For example:

ts
const { data, error } =
  await supabase.auth.signUp({
    email,
    password,
  });

You can use the same Server Action structure as the login example.

However, signup is not always equivalent to immediate login.

Email confirmation matters

Depending on your Supabase Auth configuration, new users may need to confirm their email address before they can sign in.

Your signup interface should therefore display an appropriate message, such as:

"Check your email for a confirmation link."

Do not automatically redirect every new signup to an authenticated dashboard.

What about confirmation redirects?

SSR applications commonly need a dedicated confirmation route.

The flow can involve an email link containing a token hash, which your server-side route exchanges or verifies according to the configured Supabase email template and authentication flow.

Follow Supabase's password-based SSR documentation to implement that route correctly.

The placeholder app/auth/confirm/route.ts in our folder structure is not an implemented confirmation handler.

If you need working signup confirmation, password reset, or OAuth redirects, complete and test those flows before production deployment.

11. Protect Dashboard Pages Correctly

A common recommendation in older Next.js tutorials is to place one authentication check in a protected layout.

For example:

text
app/
└── (workspace)/
    ├── layout.tsx
    └── dashboard/
        └── page.tsx

You can use layouts to render a dashboard shell and show user-specific navigation.

But don't rely on a layout as your only security check.

Next.js layouts do not necessarily rerender during every navigation.

Also, Server Actions and Route Handlers can be invoked separately from the page that displays their controls.

Create a reusable authentication helper

Create:

src/lib/auth/require-user.ts

ts
import "server-only";

import { redirect } from "next/navigation";

import { createClient } from "@/lib/supabase/server";

export async function requireUser() {
  const supabase = await createClient();

  const { data, error } =
    await supabase.auth.getClaims();

  if (error || !data?.claims?.sub) {
    redirect("/login");
  }

  return data.claims.sub;
}

The helper verifies the caller's authentication token and returns the subject identifier.

getClaims() is suitable for verifying JWT identity.

If the application needs the latest user record from Supabase Auth, use getUser() instead.

Neither method automatically proves that the user has access to a particular organization, project, or administrative operation.

Use it in a protected page

tsx
// src/app/dashboard/page.tsx

import { requireUser } from "@/lib/auth/require-user";

export default async function DashboardPage() {
  await requireUser();

  return (
    <main>
      <h1>Dashboard</h1>
      <p>You are signed in.</p>
    </main>
  );
}

This example protects the page's rendering.

But it does not replace checks inside data-fetching functions or mutations.

12. Enforce Authorization with Supabase RLS

Authentication identifies the user.

RLS determines which database rows the user may access.

For example, suppose your application stores private notes.

sql
create table public.notes (
  id uuid primary key default gen_random_uuid(),

  user_id uuid not null
    references auth.users(id),

  content text not null
);

alter table public.notes
enable row level security;

Grant authenticated users read access:

sql
revoke all on public.notes
from anon, authenticated;

grant select on public.notes
to authenticated;

Then add an ownership policy:

sql
create policy "Users read own notes"
on public.notes
for select
to authenticated
using (
  (select auth.uid()) = user_id
);

Now the database filters rows according to the caller's authenticated identity.

You should still validate authentication in sensitive server operations and apply any additional business permissions.

For an application where users can create, update, or delete notes, define separate write policies and appropriate grants.

Important: This is a standalone illustrative table. Review existing privileges, policies, and schemas before adapting SQL to a real application.

13. Implement Logout

Logout can also use a Server Action.

Add this to your authentication actions module:

ts
export async function logout() {
  const supabase = await createClient();

  const { error } = await supabase.auth.signOut();

  if (error) {
    throw new Error("Unable to sign out");
  }

  redirect("/login");
}

Because this example uses the server client, it can update the relevant cookies through the request's supported write context.

For example, a dashboard can render a form:

tsx
import { logout } from "@/features/auth/actions";

export function LogoutButton() {
  return (
    <form action={logout}>
      <button type="submit">
        Sign out
      </button>
    </form>
  );
}

After signout, verify that the application no longer grants access to authenticated data.

Also consider whether stale client-side data should be cleared or refreshed.

14. Understand getClaims(), getUser(), and getSession()

Supabase provides several methods for working with authentication state.

They serve different purposes.

getClaims()

Use this when you need to verify the identity represented by the current access token.

It validates the token's signature.

For projects using asymmetric signing keys, verification can happen locally against published signing keys. Other signing configurations may require a network-based verification path.

It does not retrieve the latest user database record.

getUser()

Use this when you need current user information from Supabase Auth.

It makes a request to the Auth service and returns the user record when the session is valid.

This can be useful when fresh account state matters.

getSession()

Use this when you need session data such as access or refresh tokens for an appropriate operation.

Do not trust the user object obtained from an unverified cookie session as the basis for server-side authorization.

Which should you use?

For basic server-side identity verification, prefer getClaims().

For current Auth user information, use getUser().

For raw session management, getSession() has its own role, but it should not replace verified identity checks.

These are not interchangeable authentication shortcuts.

15. Common Next.js and Supabase Auth Mistakes

Mistake 1: Using browser-only storage for server authentication

Server Components cannot access localStorage.

Use the SSR client and cookie-based authentication flow.

Mistake 2: Forgetting session refresh

If your application doesn't correctly refresh expiring tokens, authenticated sessions may become unreliable.

Configure Proxy or Middleware according to the Next.js version you're using.

Mistake 3: Protecting only the layout

A layout check does not automatically secure every Server Action, Route Handler, or database operation.

Enforce access checks close to the data.

Mistake 4: Trusting getSession() for authorization

An unverified cookie-derived session must not be treated as proof of identity.

Use the appropriate verification method.

Mistake 5: Exposing privileged credentials

Never expose Supabase secret or service-role credentials in browser-side code.

Mistake 6: Forgetting email confirmation

Newly registered users may need to confirm their email address.

Build the signup and confirmation flows according to the project's Auth settings.

Mistake 7: Redirect loops

Authentication redirects can conflict if the login page, Proxy, and protected routes all redirect without consistent conditions.

Keep redirects simple, ensure login remains reachable, and test logged-in and logged-out behavior.

Mistake 8: Accidentally caching private responses

Authenticated pages and token-refresh responses require careful cache handling.

A response containing user-specific data or Set-Cookie headers must not be shared between unrelated users through an incorrectly configured cache.

Review caching and CDN behavior before deployment.

16. Test Your Authentication Flow

Before using the implementation in production, verify the full workflow.

Test 1: Successful login

Sign in using a valid test account.

Expected result: the user reaches the dashboard with a valid authenticated session.

Test 2: Invalid credentials

Enter the wrong password.

Expected result: the application displays a safe error without signing the user in.

Test 3: Protected page access

Open /dashboard without being signed in.

Expected result: the application redirects to the login page or otherwise denies access.

Test 4: Refresh the page

Sign in, refresh the browser, and revisit the dashboard.

Expected result: the authenticated session remains usable.

Test 5: Session refresh

Test an expired or nearly expired access token using an appropriate controlled test setup.

Expected result: an eligible session refreshes correctly without exposing credentials or causing a redirect loop.

Test 6: Cross-user database access

Create two independent users.

Attempt to access another user's protected data.

Expected result: unauthorized access is denied by the database policies.

Test 7: Logout

Sign out and try visiting the dashboard again.

Expected result: protected content is not accessible.

Test 8: Signup confirmation

If email confirmation is enabled, verify the confirmation email, callback route, and resulting authenticated state.

Verification note: These are expected outcomes, not independently executed test results. The code examples should be integration-tested against the installed Next.js and Supabase package versions before production deployment.

When Should You Choose Auth.js Instead?

Supabase Auth is not the best solution for every project.

If your application already uses Auth.js, migrating purely to reduce dependency count may create unnecessary work.

Auth.js may also be a good fit when your application needs specific providers, adapters, or authentication integrations that work well with its architecture.

Supabase Auth is a strong option when the application already depends on Supabase PostgreSQL and you want authentication to integrate naturally with its database authorization features.

The choice should depend on your application's requirements, not on the assumption that one library is universally simpler or more secure.

Final Thoughts

You can build authentication in Next.js without NextAuth by using Supabase Auth and @supabase/ssr.

The core implementation has a clear structure:

  • A browser client handles browser-side authentication.
  • A server client reads and updates cookie-backed sessions.
  • Proxy manages token refresh across requests.
  • Server Actions handle login and logout.
  • Verified identity checks protect server-side operations.
  • Supabase RLS restricts access to database records.

But the most important lesson is that authentication and authorization are different responsibilities.

A successful login doesn't automatically mean a user can access every protected record.

A route that redirects unauthenticated visitors doesn't automatically secure its APIs.

Use verified identity checks, enforce permissions near your data, and test the complete session lifecycle.

That gives you a much stronger foundation for building secure Next.js applications with Supabase.

Official Documentation

Keep the conversation useful

Found a different result?

Include your framework version, the error, and the steps to reproduce it. Specific details help improve the article for the next reader.

Send a correction or question

Share this article