Logo

dev-resources.site

for different kinds of informations.

Adding Clerk Authentication to a NextJS App

Published at
3/19/2024
Categories
nextjs
clerk
security
typescript
Author
brianmmdev
Categories
4 categories in total
nextjs
open
clerk
open
security
open
typescript
open
Author
10 person written this
brianmmdev
open
Adding Clerk Authentication to a NextJS App

I’m the type that needs a realistic project to work on if I’m going to understand a platform.

So I decided that to really learn Clerk, I want to create user profile pages on the website of my Discord server. Since Clerk has a great suite of components for Next.js apps, I figure why not port over the site to Next at the same time to learn both platforms. The first step was to bootstrap a Next site and get authentication set up so I can have users sign into it.

So here’s a quick guide on how to configure Clerk with a Next app.

Creating the Clerk Application

Starting over in Clerk, I’m going to create a new project here. I’m going to just configure Google as my SSO provider so I can sign in with my Google account. All other methods are disabled.

Creating an application in Clerk

After the application is created, the variables shown on the following page will be used in the Next project, so note these down for the next section.

The environment variables to be used in the Next app

Setting up Next

I have a basic Next app set up here, and I’m going to start by installing the Clerk components.

Installing the Clerk libraries

I’m going to create a new file named .env.local and put the environment variables from the previous section of this article in there. These env vars will be used by the Clerk libraries to connect up to the application that was created earlier in the article.

Setting up the environment variables

Next I’m going to set up the middleware by creating middleware.ts and putting the following code in there. By default, this middleware will protect the entire site so I’ll also need to explicitly specify my public routes. In this case, it’s just the root.

Adding the auth middleware

Then I’ll update layout.tsx and wrap the entire app in which will enable security on the app.

Wrapping the layout in the provider

Then I’ll add the component to the home page, which will let me sign in with my Google account.

Adding the SignUpButton

Here is what the rendered version of this looks like.

The Next app with a Sign up button

Clicking that will bring me to Clerk’s UI which I can use to perform all of the actions needed to either create an account or sign in with an existing account.

The Clerk login

After signing in with my Google account, I’m automatically redirected back to the home page but there’s no indication that I’m signed in. This can be fixed using the useUser hook from Clerk. It can be used to check to see if the user is signed in and display the component instead. Note that this needs to be rendered on the client so I added 'use client' to the page.

Adding the UserButton to the Next app

Now the home page should show my user profile image that has a menu embedded.

The Next app with the UserButton

Protecting an API route

Once logged in, Clerk will save a cookie in the browser that has tokens it can use for authentication. These cookies are sent with every backend request. The Clerk libraries also have a set of backend functions that can be used in API routes to make sure that the person signed in is authorized to call those routes. Lets explore how to do this.

The following API route will check to see if the user is signed in and simply echo back their ID in a JSON response. Passing the request (which contains the cookie) into authenticateRequest will both determine if the request is authenticated, as well as provide a helper function to get details about the user.

The API route that parses the user ID

Now if I update the front end to simply call this route on page load, you can see in the console of the browser that my Clerk user ID is being sent back to me.

The Next app with the user ID in the console

If I log out and refresh the page, it returns a 404 instead now.

The Next app with a 401 status in the console

Let me know if this was helpful, or if there are any other topics you’d like to see covered!

clerk Article's
30 articles in total
Favicon
Using Clerk SSO to access Google Calendar and other service data
Favicon
Upload to S3
Favicon
Building Multi-Tenant Apps Using Clerk's "Organization" and Next.js
Favicon
How to secure Liveblocks Rooms with Clerk in Next.js
Favicon
Simplifying Authentication in React Applications with Clerk
Favicon
Clerk Update – November 12, 2024
Favicon
Create a Simple Authentication System for your Next Application with Clerk
Favicon
Implementing Authentication with Clerk in Next.js
Favicon
Configuring Clerk.io on t3 with tRPC
Favicon
Securing Node.js Express APIs with Clerk and React
Favicon
How to Manage User Authentication in React.js, Next.js, Vue.js, and Nuxt.js Using Clerk
Favicon
Role-based access control with Clerk Organizations
Favicon
How to build reusable loaders for Remix
Favicon
Per-user B2B monetization with Stripe and Clerk Organizations
Favicon
Building Secure Authentication Systems with Next.js and Clerk 🚀🔒
Favicon
Top User Authentication Tools for Developers
Favicon
Clerk Update — July 2024
Favicon
Building a Hybrid Sign-Up/Subscribe Form with Stripe Elements
Favicon
Build a waitlist with Clerk user metadata
Favicon
Unlocking the Power of Convex and Clerk: A Guide to Seamless Authentication and Data Management
Favicon
Preventing account sharing with Clerk
Favicon
How to secure API Gateway using JWT and Lambda Authorizers with Clerk
Favicon
How to Handling Authentication in Next.js with Clerk
Favicon
What are passkeys and how do they work?
Favicon
NextAuth.js over Clerk
Favicon
Auth with Clerk
Favicon
Creating Webhook between Clerk and DynamoDB
Favicon
Next.js authentication using Clerk, Drizzle ORM, and Neon
Favicon
API Testing with Clerk and Express
Favicon
Adding Clerk Authentication to a NextJS App

Featured ones: