Next.js Quickstart
Protect your Next.js application with Clerk auth in less than ten minutes. This guide will show you how to install Clerk, add middleware to protect specific routes, and embed the <UserButton />
component for account management.
Install @clerk/nextjs
Clerk's Next.js SDK has prebuilt components, React hooks, and helpers to make user authentication easier.
To get started using Clerk with Next.js, add the SDK to your project:
Add <ClerkProvider>
to your app
All Clerk hooks and components must be children of the <ClerkProvider>
component, which provides active session and user context.
Select your preferred router to learn how to make this data available across your entire app:
Add authentication to your app
Now that Clerk is installed and mounted in your application, you can decide which pages are public and which should require authentication to access:
- Create a
middleware.ts
file at the root of your project, or in yoursrc/
directory if you have one. - In your
middleware.ts
file, export Clerk'sauthMiddleware()
helper. This helper enables authentication and blocks access for signed out visitors on routes that your middleware runs on.
Next.js middleware only runs on routes specified with matcher
. Add the following code to your middleware.ts
to protect your routes:
Try accessing your app
Access your app to verify that authentication is enabled:
- Run your project with the following terminal command from the root directory of your project:
- Visit
http://localhost:3000
to access your app. The Middleware will redirect you to your Sign Up page, provided by Clerk's Account Portal feature. - Sign up to gain access to your application.
Embed the <UserButton />
<UserButton />
is a prebuilt component that allows users to sign in, log out, and manage their account information.
Use the following code to add a <UserButton />
to your app:
Then, visit your app's homepage at localhost:3000
to see the <UserButton />
in action. It should show your avatar from the account you signed in with.
Create custom sign-up and sign-in pages
Learn how add custom sign-up and sign-in pages with Clerk components.
Read user and session data
Learn how to use Clerk's hooks and helpers to access the active session and user data in your Next.js application.
Client Side Helpers
Learn more about Next.js client side helpers and how to use them.
Next.js SDK Reference
Learn more about additional Next.js methods.
Deploy to Production
Learn how to deploy your Clerk app to production.
Deploy to Vercel
Learn how to deploy your Clerk app to production on Vercel.
Clerk + Next.js App Router Quickstart Repo
The official companion repo for Clerk's Next.js Quickstart using App Router.
Clerk + Next.js Pages Router Quickstart Repo
The official companion repo for Clerk's Next.js Quickstart using Pages Router.
Feedback
Last updated on