惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园 - 叶小钗
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Security Blog
Microsoft Security Blog
罗磊的独立博客
大猫的无限游戏
大猫的无限游戏
美团技术团队
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
aimingoo的专栏
aimingoo的专栏
腾讯CDC
WordPress大学
WordPress大学
Apple Machine Learning Research
Apple Machine Learning Research
F
Fortinet All Blogs
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog
Microsoft Azure Blog
Microsoft Azure Blog
小众软件
小众软件
Engineering at Meta
Engineering at Meta
博客园_首页
B
Blog RSS Feed
D
Docker
M
MIT News - Artificial intelligence
爱范儿
爱范儿
I
InfoQ

Clerk Blog

Going to production with Clerk Deploy Clerk Init: The fastest way to start a new project Introducing Clerk CLI Middleware-based route protection bypass Postmortem: Clerk System Outage (March 10, 2026) Clerk for the AI era Add API Key support to your SaaS in minutes Postmortem: Clerk System Outage (February 19, 2026) Using Clerk in a React Native app Postmortem: DNS Provider Outage (February 10, 2026) How do I implement passkeys in Next.js? Clerk ranked #4 fastest-growing software vendor on Ramp’s December 2025 list How do I handle JWT verification in Next.js? Committing to Agent Identity: Clerk raises $50m Series C from Menlo and Anthropic’s Anthology Fund What is the best way to handle authentication in Next.js App Router? Postmortem: Database Incident (September 14–18, 2025) How do I add authentication to a Next.js app? Introducing Free Trials in Clerk Billing Postmortem: August 28, 2025 - elevated API latency and errors Introducing Mosaic: Bring Your Brand to Every Authentication Flow Multi-tenant authentication: What you need to know (and how Clerk helps) What are the risks and challenges of multi-tenancy? Resilience in Practice: Regional Failover at Clerk Build a Cross-Platform B2B App with Clerk, Expo, and Supabase Highlights from the MiduDev/Clerk Hackathon Add multi-tenancy to an app built with Clerk, Lovable, and Supabase How to build an AI coding rules app with Clerk, Lovable, and Supabase How to Build Multi-Tenant Authentication with Clerk Choosing the right SaaS architecture: Multi-Tenant vs. Single-Tenant Postmortem: June 26, 2025 service outage
Next.js 13 Routes Part 2: Implementing Protected Routes
Aniket Bhattacharyea · 2023-01-26 · via Clerk Blog

In part one of this series, you learned about Next.js API routes and how to protect API routes with JWT authentication. In this part, you'll learn how to create protected routes using React Context as well as how using Clerk makes this process easier.

Exploring the Starter App

To get started, a starter app already has been made that you can clone from GitHub:

The app will start running at localhost:3000.

The posts page can be found at http://localhost:3000/posts, which shows a list of all the posts.

List of all posts

This page has a companion API route that returns all the posts in JSON:

The data for posts is stored in data.js.

The /api/auth/login route implements JWT authentication and returns a JWT when the correct username and password combination is supplied:

Finally, the /api/users/me route returns the currently authenticated user, provided a valid JWT is passed in the header:

The user profiles can also be found in data.js.

The goal of the article is to protect the /api/posts API route and the /posts page using the JWT authentication strategy. In part one, you saw how JWT authentication can be added to API routes using the jwt.verify method. However, it's resource intensive to manually verify and decode the JWT in every single API route. It's also tedious to manually include the authentication header in every request that you make from a page.

In this article, you'll learn how to "share" an authenticated session across all pages by using an AuthContext. You'll also refactor the JWT verification to a withAuth wrapper that will make it easy to protect API routes. Finally, you'll see how using Clerk makes this process smooth and seamless.

Implementing AuthContext

AuthContext is simply a React Context that will make it easy to pass required authentication parameters throughout the app. To implement this, first install the required libraries:

js-cookie will be used to store the JWT in the browser's cookie. axios makes it easy to preconfigure a default API service with headers. You'll use this to include the token in the headers once the user logs in.

Create a file named api.js in the project root:

Here, an instance of axios is created that will be used to make API calls later.

Create the file auth_context.js:

The most important bits in the above Context are the fetchUserFromCookie, login, and logout functions. The fetchUserFromCookie function fetches the token from the cookie and sets the authorization header in the default api instance.

It then makes a call to /api/users/me to retrieve and store the authenticated user. The login function logs in the user through the /api/auth/login route and stores the token in the cookie. The logout function deletes the user, the cookie, and the authorization header.

Finally, create the withAuth function that'll protect the API routes by wrapping the handlers:

You can now modify pages/api/posts.js to include withAuth:

Note that only the posts by the logged in user are returned. The logged in user is found through req.auth.user.

Let's now create the login page. First, add Formik and Yup. These are not strictly required but will help in creating the login form.

Create pages/login.js:

This page uses the login function described above to log in the user.

Now update pages/posts.js to make use of AuthContext:

Finally, update pages/_app.js to wrap everything in AuthProvider:

Start the server with yarn dev and visit http://localhost:3000/login. Log in with the credentials (you can find the username in data.js and the password is "password") and you'll be redirected to the posts page. You can verify that you're only seeing posts from the logged in user.

The final app for this section can be found in the manual branch of the GitHub repo.

Authentication with Clerk

In this section, you'll replace the manual authentication with Clerk. Before starting with Clerk, you should revert the changes you've made so far. You can simply run git stash && git clean -fdx to stash your changes.

First, create an application in Clerk. You can keep all the default options.

Creating an application in Clerk

Once the application is created, go to the API keys page and copy the frontend API key, the backend API key, and the JWT verification key. Paste these into .env:

Install the required library:

Wrap pages/_app.js with Clerkprovider:

The publicPages array decides which pages will not be protected under authentication. For a protected page, if the user is not signed in, they will be redirected to the login page.

Create the file middleware.js in the project route:

Modify pages/api/posts.js to include the getAuth function that authenticates the user with Clerk:

In the Clerk dashboard, go to the Users page and create a test user.

Creating a new user

After the user is created, open the record and copy the ID as shown below.

Copying user ID

Open data.js and replace the numeric id field of any one user and the userId field in the posts array:

Run the server again with yarn dev. Visit http://localhost:3000/posts and you should be redirected to Clerk's login page.

Clerk's login page

After logging in, you'll be redirected back to the /posts page. Verify that you can see only the posts corresponding to the logged in user.

The posts page

Conclusion

Protecting Next.js routes with authentication is a vital part of developing any web app. However, manually creating authentication mechanisms can be tedious and time-consuming. A solution like Clerk’s Next.js authentication comes with all the bells and whistles so that you don't need to worry about auth and can focus on the core app instead.