Connect your clerk.com instance to your Next.js in minutes to start serving protected pages and authenticate users.
Clerk provides a comprehensive solution for user sign up, sign in, email verification and authentication solution and hassle-free session management and it seamlessly integrates with Next.js making the whole process a breeze.
Let’s dive in and set up Clerk in your Next.js application.
1. Install clerk for Next.js
Run npm install @clerk/nextjs
to install clerk for Next.js
Then, open the main layout.tsx file in your Next.js project and add Clerk provider:
This will enable Clerk for all children components.
2. Register with clerk.com and generate API keys
First, you need to register an account with clerk.com. They offer a fully-fledged solution with generous free tier of 1000 Monthly Active Users so you don’t need to worry about upfront costs.
Generate development API keys for your Next.js integration by going to Developers -> API Keys
:
Then copy the NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY
and CLERK_SECRET_KEY
keys to your local Next.js’s .env file (and to Vercel platform too if you are going to publish your app there):
Now you’re all set and you can start using Clerk! Let’s move on to do something cool with it.
3. Protect routes with Clerk middleware
Now we’ve setup basic clerk and its provider we can define routes that need to be protected and only visible to authenticated users.
In order to do this you need to configure Clerk middleware in your Next.js project where you define which routes are only accessible to authenticated users.
You do this by placing the middleware.tsx
file in the root of your Next.js project (one folder above the app
folder) and by specifying which routes must be protected:
import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server'
const isProtectedRoute = createRouteMatcher(['/secret(.*)', '/app(.*)'])
export default clerkMiddleware(async (auth, req) => {
if (isProtectedRoute(req)) await auth.protect()
})
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)(.*)',
],
}
As you can see the default exported function runs the auth.protect
async function that checks whether if the route created in the createRouteMatcher
function is included in the protected url path(s) and ensures only authenticated users are allowed to access these paths.
4. Add UserButton from Clerk
Now we’re all set and can add user sign up and sign in button to the site to authenticate users and allow them accessing them the restricted parts of the app.
To do this import the following functions from Clerk module:import { SignedIn, SignedOut, UserButton, SignInButton } from '@clerk/nextjs'
And display different children components depending on if the user is logged in or logged out. In this example I used created a the SignInButton provided by Clerk that allows users to Sign In if they haven’t already:
import { SignedIn, SignedOut, UserButton, SignInButton } from '@clerk/nextjs'
export default function User() {
return (
<>
<SignedOut>
<SignedIn >
<UserButton
userProfileUrl="/"
appearance={{
elements: {
userButtonAvatarBox: {
width: 40,
height: 40,
},}}}/>
</SignedIn>
<SignedOut />
<SignInButton/>
</SignedOut>
</>
)
}
That’s it! You’ve just configured Clerk for your Next.js project and can handle users sign up, sign in, session management and route protection!
5. Clerk hooks for user management
To get your users’ metadata from Clerk you can use the useUser hook from Clerk module:import { useUser } from '@clerk/nextjs'
This hook provides all details and metadata from Clerk database about the current logged in user such as email, name (if you enabled it in Clerk management console) and other useful data you can use to display your users profile on the website.
I hope that helped. Happy coding!