Back to blog

Published on Thursday, December 26, 2024

Setting up Clerk with Next.js

Setting up Clerk with Next.js

Prerequisites

Ensure you have the following:

Video Tutorial

Step 1: Install Clerk

First, install the required Clerk packages

npm install @clerk/nextjs

Step 2: Setup API Keys

In the .env.local file, add the following keys from your Clerk dashboard:

.env.local
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your_publishable_key
CLERK_SECRET_KEY=your_secret_key

Step 3: Add Clerk Provider to your app

Wrap your entire app with ClerkProvider at the entry point to provide global session and user context for Clerk's hooks and components. For more options, see the reference docs.

// app/layout.tsx
import {
  ClerkProvider,
  SignInButton,
  SignedIn,
  SignedOut,
  UserButton
} from '@clerk/nextjs'

import './globals.css'

export default function RootLayout({
  children
}: {
  children: React.ReactNode
}) {
  return (
    <ClerkProvider>
      <html lang="en">
        <body>
          <header>
            <SignedOut>
              <SignInButton />
            </SignedOut>
            <SignedIn>
              <UserButton />
            </SignedIn>
          </header>
          <main>{children}</main>
        </body>
      </html>
    </ClerkProvider>
  )
}

Step 4: Protect Routes with Middleware

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)(.*)',
  ],
}

By default, clerkMiddleware() doesn't protect routes. Enable protection manually for specific routes see the reference docs for details.

Note:

If using a src directory, create middleware.ts inside it. Otherwise, place middleware.ts at the project root with package.json and package-lock.json.

Step 5: Create Your First User

Run your app with:

npm run dev

Go to http://localhost:3000 and sign up to create your first user, fully powered by Clerk’s authentication.

Conclusion

Integrating Clerk with Next.js App Router streamlines user authentication, providing a secure and efficient solution. With this setup, you're ready to build robust applications with seamless authentication.