Oct 04, 2022
Colin Sidoti
New in 4.5: Authentication moves to middleware, switchable runtime support, improved developer experience, preparation for Layouts
Version 4.5 of @clerk/nextjs brings sweeping improvements to server-side authentication in Next.js.
Get started with npm i @clerk/nextjs@latest
Going forward, developers will authenticate requests once in Next.js middleware
middleware.js example:
import { withClerkMiddleware } from "@clerk/nextjs/server";export default withClerkMiddleware((req) => {// Your own middleware});
API routes example:
import { getAuth } from "@clerk/nextjs/server";export default function handler(req, res) {const { userId } = getAuth(req);// ...});
getServerSideProps example:
import { getAuth } from "@clerk/nextjs/server";export const getServerSideProps = ({ req }) => {const { userId } = getAuth(req);// ...};
With this change, authentication in Next.js will finally feel familiar for developers who have worked with frameworks like Express or Ruby on Rails, where authentication is normally handled within middleware.
Next.js 12.2 brought a switchable runtime, so developers could choose between a node runtime or an edge runtime for each of their API routes and server-rendered pages.
Our new getAuth() helper is isomorphic, so it works regardless of the runtime you choose.
If you've used Clerk in the past, you'll notice three small but delightful improvements to our developer experience:
1// pages/api/foo.js2import { getAuth } from "@clerk/nextjs/server";34export default function handler(req, res) {5const { userId } = getAuth(req);6// ...7});8910// pages/bar.js11import { getAuth } from "@clerk/nextjs/server";1213export const getServerSideProps = ({ req }) => {14const { userId } = getAuth(req);15// ...16};171819// middleware.js20import { withClerkMiddleware, getAuth } from "@clerk/nextjs/server";2122export default withClerkMiddleware((req) => {23const { userId } = getAuth(req);24// ...25});
1// pages/api/foo.js2import { withAuth } from '@clerk/nextjs/api';34export default withAuth((req, res) => {5const { userId } = req.auth;6// ...7});8910// pages/bar.js11import { withServerSideAuth } from "@clerk/nextjs/ssr";1213export const getServerSideProps = withServerSideAuth(({ req }) => {14const { userId } = req.auth;15// ...16});171819// middleware.js20// Clerk hasn't supported Next.js 12.2+ middleware until today2122232425
Our team has been watching the Next.js Layouts RFC
We expect that by computing the authentication state in middleware, we'll be able to share it with each of your parallel-loading layout files.
Get started right away with our guide to Next.js authentication, or join our community Discord
Start completely free for up to 10,000 monthly active users and up to 100 monthly active orgs. No credit card required.
Learn more about our transparent per-user costs to estimate how much your company could save by implementing Clerk.
The latest news and updates from Clerk, sent to your inbox.