Usage & Integration

Learn how to implement Clerk’s authentication features, such as sign-in, protected routes, and user management, in your app.

Clerk provides components and hooks for authentication flows, integrated into Plainform Dev’s Next.js structure, allowing you to manage user sessions and protect routes easily.

Implementing Authentication

Add Authentication Components

  • Use Clerk’s <SignIn /> or <SignUp /> in app or components. Example:
@/app/sign-in/page.tsx
import { SignIn } from '@clerk/nextjs';

export default function SignInPage() {
  return <SignIn />;
}

Protected Routes

  • Restrict access using Clerk’s auth or middleware. Example:
middleware.ts
import { auth } from "@clerk/nextjs";

export default function ProtectedPage() {
  const { userId } = auth();
  if (!userId) return <div>Please sign in</div>;
  return <div>Protected content</div>;
}

Manage user Data

  • Use Clerk hooks like useUser in components:
@/app/components/UserMenu.tsx
import { useUser } from '@clerk/nextjs';

export default function UserMenu() {
  const { user } = useUser();
  return <div>Welcome, {user?.firstName}</div>;
}

Verify Configuration

  • Run npm run dev to validate keys via t3-env (in env.mjs).
  • Check the Clerk dashboard if validation fails.

Handle Webhooks (Optional)

  • Configure CLERK_WEBHOOK_SECRET in .env for webhook verification.
  • Create an API route (e.g., app/api/webhooks/clerk/route.ts) for webhook events.

Testing Authentication

  • Run npm run dev and test /sign-in or /sign-up pages.
  • Verify protected routes restrict unauthenticated users.
  • Check user data rendering with Clerk hooks.
  • Monitor user activity in the Clerk dashboard.

Important Notes

  • Environment Variables: Ensure NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY and CLERK_SECRET_KEY are valid, or t3-env will block startup.
  • Customization: Adjust Clerk’s UI (e.g., branding, themes) in the dashboard to match your app.
  • Security: Keep CLERK_SECRET_KEY and CLERK_WEBHOOK_SECRET out of client-side code and version control.

By following these steps, you can leverage Clerk’s robust authentication features in Plainform Dev, streamlining user management for your SaaS. For advanced features like social logins or 2FA, consult the Clerk documentation.

How is this guide ?

Last updated on