Integrating Clerk Authentication in a Next.js App and Syncing Users with a Database

Introduction

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.

Setting Up a Next.js App

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

Installing Clerk

To integrate Clerk, install the official Clerk SDK for Next.js.

npm install @clerk/nextjs

Configuring Clerk in Next.js

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>
  );
}

Adding Authentication Components

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>
  );
}

Protecting Routes with Clerk

Use Clerk’s withAuth to protect specific routes.

import { withAuth } from '@clerk/nextjs';
export default withAuth(
  (req) => {
    return { props: {} };
  },
  { publicRoutes: ['/'] }
);

Fetching User Data with Clerk

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>;
}

Syncing User Data with a Database

To store authenticated users in a database, use Clerk’s Webhooks or Next.js API routes with Prisma or MongoDB.

Storing User Data in a Database

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?
}

Creating an API Route to Sync Users

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);
}

Triggering User Sync on Authentication

Call the sync API after login or signup.

useEffect(() => {
  fetch('/api/sync-user', { method: 'POST' });
}, []);

Deploying Your Next.js App with Clerk

To deploy your app, use Vercel.

vercel deploy

Conclusion

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!