Skip to main content

Adding Authentication

info

Before continuing, ensure your workstation has been set up with the Core Components, as well as components specific to the language ecosystem you're working in: [JavaScript] [Java] [.Net] [Python] [Rust]

For adding authentication to your Next.js apps, we recommend two approaches.

Setting up NextAuth

Install NextAuth to your project

pnpm add next-auth

Add API route

In App Router, we can leverage the new Route Handlers to add the API route. Start by creating a file called /app/api/auth/[...nextauth]/route.ts. This contains the dynamic route handler for NextAuth.js which will also contain all of your global NextAuth.js configurations.

// /app/api/auth/[...nextauth]/route.ts
import NextAuth from "next-auth"

const handler = NextAuth({
...
})

export { handler as GET, handler as POST }

Add Session Provider

To allow accessing sessions in client components, add a <SessionProvider /> in the Root Layout

'use client';

import { SessionProvider } from 'next-auth/react';
import { ReactNode } from 'react';
export default function NextAuthProvider({
children,
}: {
children: ReactNode;
}) {
return <SessionProvider>{children}</SessionProvider>;
}

Environment

When deploying to production, set the NEXTAUTH_URL environment variable to the canonical URL of your site. NEXTAUTH_URL=https://example.com

The NEXTAUTH_SECRET is used to encrypt the NextAuth.js JWT, and to hash email verification tokens. To autogenerate one, you can run

npx auth secret

in your project's root, and it will autogenerate a random value and put it in your .env.local file.

Usage

In Server Components, you can use getServerSession:

import { getServerSession } from "next-auth/next"
import { authOptions } from "pages/api/auth/[...nextauth]"

export default async function Page() {
const session = await getServerSession(authOptions)
return <pre>{JSON.stringify(session, null, 2)}</pre>
}

In Client Components, you can use the useSession hook:

'use client';
import { useSession } from 'next-auth/react';
export default function ClientComponent() {
const { data: session, status } = useSession();
return (
<div>
ClientComponent {status}{' '}
{status === 'authenticated' && session.user?.name}
</div>
);
}

To see more advanced use cases, visit the official NextAuth documentation.

Setting up Clerk.js

Register a Clerk Application

Go to https://dashboard.clerk.com/sign-up and sign up for a free account. Then navigate to create a new application for which we can generate credentials. After your application is created, the following page will show you the environment variables needed for the project.

Install Clerk

pnpm add @clerk/nextjs

Add Clerk middleware to your project

If you're using the /src directory, create middleware.ts in the /src directory, otherwise create middleware.ts in the root directory. In your middleware.ts file, export the clerkMiddleware() helper:

// middleware.ts
import { clerkMiddleware } from '@clerk/nextjs/server'

export default clerkMiddleware()

export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
'/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
// Always run for API routes
'/(api|trpc)(.*)',
],
}

Add <ClerkProvider> and Clerk components to your app

Add the <ClerkProvider> component to your app's layout. This component provides Clerk's authentication context to your app.

// app/layout.tsx
...
export const metadata: Metadata = {
title: 'Clerk Next.js Quickstart',
description: 'Generated by create next app',
}

export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<ClerkProvider>
<html lang="en">
<body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
<header className="flex justify-end items-center p-4 gap-4 h-16">
<SignedOut>
<SignInButton />
<SignUpButton />
</SignedOut>
<SignedIn>
<UserButton />
</SignedIn>
</header>
{children}
</body>
</html>
</ClerkProvider>
)
}

Usage

Client-side helpers

Because the Next.js SDK is built on top of the Clerk React SDK, you can use the hooks that the React SDK provides. These hooks include access to the Clerk object, User object, Organization object, and a set of useful helper methods for signing in and signing up.

  • useUser()
  • useClerk()
  • useAuth()
  • useSignIn()
  • useSignUp()
  • useSession()
  • useSessionList()
  • useOrganization()
  • useOrganizationList()

Server-side helpers

The following methods integrate Clerk features into apps using the latest App Router and React Server Components features.

  • auth()
  • currentUser()
  • Route Handlers
  • Server Actions