Add authentication and user management to your Next.js app with Clerk
You will learn how to:
- Install
@clerk/nextjs
- Set up your environment keys
- Wrap your Next.js app in
<ClerkProvider/>
- Limit access to authenticated users
- Embed the
<UserButton/>
Prerequisites
Quickstart
Install @clerk/nextjs
Clerk's Next.js SDK gives you access to prebuilt components, hooks, and helpers for Next.js Server Components, Route Handlers and Middleware. Install it by running the following command in your terminal:
terminalnpm install @clerk/nextjs
terminalyarn add @clerk/nextjs
terminalpnpm add @clerk/nextjs
Set environment keys
In your Next.js project's root folder, you may have an .env.local
file alongside package.json
and other configuration files. If you don't see it, create it.
Add the following code to your .env.local
file to set your public and secret keys.
Pro tip! If you are signed into your Clerk Dashboard, your keys should become visible by clicking on the eye icon.
.env.localNEXT_PUBLIC_CLERK_PUBLISHABLE_KEY={{pub_key}} CLERK_SECRET_KEY={{secret}}
This sets your public and secret keys.
Wrap your app in <ClerkProvider />
The <ClerkProvider />
component provides active session and user context to Clerk's hooks and other components. Import it into your app by adding import { ClerkProvider } from '@clerk/nextjs'
at the top of your file.
The app/layout.tsx
file might be in your src
folder if it isn't in your root folder.
For this project, it makes sense to wrap the <html />
element with <ClerkProvider />
. This makes the active session and user context accessible anywhere within the app.
/src/app/layout.tsximport { ClerkProvider } from '@clerk/nextjs' export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( <ClerkProvider> <html lang="en"> <body>{children}</body> </html> </ClerkProvider> ) }
The root layout is a server component. If you plan to use the <ClerkProvider />
outside the root layout, it will need to be a server component as well.
For this project, it makes sense to wrap the <Component />
element with <ClerkProvider />
. This makes the active session and user context accessible anywhere within MyApp
.
_app.tsximport '@/styles/globals.css' import { ClerkProvider } from "@clerk/nextjs"; import type { AppProps } from "next/app"; function MyApp({ Component, pageProps }: AppProps) { return ( <ClerkProvider {...pageProps}> <Component {...pageProps} /> </ClerkProvider> ); } export default MyApp;
Require authentication to access 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. If your application uses the src/
directory, your middleware.ts
file should be placed inside the src/
folder. If you are not using a src/
directory, place the middleware.ts
file in your root directory alongside .env.local
.
Copy and paste the following code into your middleware.ts
. With this, your entire application is protected.
middleware.tsimport { authMiddleware } from "@clerk/nextjs"; // This example protects all routes including api/trpc routes // Please edit this to allow other routes to be public as needed. // See https://clerk.com/docs/references/nextjs/auth-middleware for more information about configuring your Middleware export default authMiddleware({}); export const config = { matcher: ['/((?!.+\\.[\\w]+$|_next).*)', '/', '/(api|trpc)(.*)'], };
Try accessing your app now by visiting http://localhost:3000
. The Middleware will redirect you to your Sign Up page. If you want to make other routes public, check out the authMiddleware reference page. Go ahead and sign up to get access to your application. Your app is now fully protected by Clerk!
Embed the <UserButton />
Clerk offers a set of prebuilt components to add functionality to your app with minimal effort. The <UserButton />
allows users to manage their account information and log out, completing the full authentication circle.
Add it anywhere inside <ClerkProvider />
in your app. First add import { UserButton } from "@clerk/nextjs";
to the top of your file. Then add <UserButton afterSignOutUrl="/"/>
. The afterSignOutUrl
prop lets you customize what page the user will be redirected to after sign out.
app/page.tsximport { UserButton } from "@clerk/nextjs"; export default function Home() { return ( <div> <UserButton afterSignOutUrl="/"/> </div> ) }
pages/index.tsximport { UserButton } from "@clerk/nextjs"; export default function Home() { return ( <> <header> <UserButton afterSignOutUrl="/"/> </header> <div>Your page's content can go here.</div> </> ); }
Sign out of your application
Visit your Next.js application at localhost:3000
, click on your avatar, and select "sign out." You are now back where you started—a sign in form.
You're authenticated!
Congratulations! Your app is now only available to authenticated users! But this is just the first step.
If you would like a repository that demonstrates many of the features Clerk has to offer, such as user, session, and organization management, check out one of Clerk's showcase repositories:
Next steps
Create custom sign-up and sign-in pages
Learn how add custom sign-up and sign-in pages with Clerk components.
Learn More
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.
Learn More
Client Side Helpers
Learn more about Next.js client side helpers and how to use them.
Learn More
Next.js SDK Reference
Learn more about additional Next.js methods.
Learn More