First we are going to install a new Nextjs project but this should work with any Nextjs App Directory project, then we will install Clerk and get it working, once it’s working we will install and embed a Sanity studio and get it ready to receive the information provided by Clerk. We will finish by creating an API route, where we will send the user data to Sanity, and verify that the user was created.
npx create-next-app@latest .
For the purpose of this tutorial I want to start with an empty home page in app/page.tsx
.
// app/page.tsx
const Home = () => {
return (
<main className="grid place-content-center min-h-screen">
Hello World
</main>
)
}
export default Home;
npm run dev
npm install @clerk/nextjs
// app/layout.tsx
import './globals.css'
import { Inter } from 'next/font/google'
import { ClerkProvider } from '@clerk/nextjs'
const inter = Inter({ subsets: ['latin'] })
export const metadata = {
title: 'Create Next App',
description: 'Generated by create next app',
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<ClerkProvider>
<html lang="en">
<body className={inter.className}>{children}</body>
</html>
</ClerkProvider>
)
}
Protect your Application
Now that Clerk is installed and mounted in your application, it’s time to decide which pages are public and which need to hide behind authentication. We do this by creating a middleware.ts
file at the root folder (or inside src/
if that is how you set up your app).
In my case I will create the middleware.ts file inside the root folder of my project. I will also add a Public Routes array, so any route you would like to be public you will need to add to this array.
We will add the studio route, and let sanity handle the auth for the CMS studio.
// middlewate.ts
import { 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/nextjs/middleware> for more information about configuring your middleware
const publicRoutes = ["/", "/studio"];
export default authMiddleware({
publicRoutes,
});
export const config = {
matcher: ["/((?!.*\\\\..*|_next).*)", "/", "/(api|trpc)(.*)"],
};