Authentication is a crucial part of any modern web application. Clerk simplifies authentication in Next.js by providing seamless user management, authentication flows, and security features. In this guide, we’ll integrate Clerk into a Next.js app and sync authenticated users with a database.
Before integrating Clerk, make sure you have a Next.js project set up. If not, create one using the following command:
npx create-next-app@latest my-app && cd my-app
To integrate Clerk, install the official Clerk SDK for Next.js.
npm install @clerk/nextjs
To use Clerk, wrap your app with ClerkProvider in `_app.js` or `_app.tsx`.
import { ClerkProvider } from '@clerk/nextjs';
export default function MyApp({ Component, pageProps }) {
return (
<ClerkProvider {...pageProps}>
<Component {...pageProps} />
</ClerkProvider>
);
}
Clerk provides built-in authentication components like SignIn and SignUp.
import { SignIn, SignUp } from '@clerk/nextjs';
export default function AuthPage() {
return (
<div>
<h1>Sign In</h1>
<SignIn />
<h1>Sign Up</h1>
<SignUp />
</div>
);
}
Use Clerk’s withAuth to protect specific routes.
import { withAuth } from '@clerk/nextjs';
export default withAuth(
(req) => {
return { props: {} };
},
{ publicRoutes: ['/'] }
);
You can access the authenticated user using useUser.
import { useUser } from '@clerk/nextjs';
export default function Dashboard() {
const { user } = useUser();
return <h1>Welcome, {user?.firstName}</h1>;
}
To store authenticated users in a database, use Clerk’s Webhooks or Next.js API routes with Prisma or MongoDB.
Set up Prisma and create a user model.
npx prisma init
// prisma/schema.prisma
model User {
id String @id @default(uuid())
email String @unique
name String?
}
Use an API route to sync Clerk users with the database.
// pages/api/sync-user.js
import { prisma } from '../../lib/prisma';
import { getAuth } from '@clerk/nextjs/server';
export default async function handler(req, res) {
const { userId, email, firstName } = getAuth(req);
const user = await prisma.user.upsert({
where: { email },
update: { name: firstName },
create: { id: userId, email, name: firstName }
});
res.status(200).json(user);
}
Call the sync API after login or signup.
useEffect(() => {
fetch('/api/sync-user', { method: 'POST' });
}, []);
To deploy your app, use Vercel.
vercel deploy
By integrating Clerk authentication with a Next.js app and syncing users with a database, you can build a secure and scalable authentication system effortlessly. Clerk simplifies authentication while Prisma or MongoDB helps manage user data efficiently. Try it in your Next.js project today!