feat: add clerk integration to next-template

This commit is contained in:
afiqzudinhadi 2025-06-23 16:32:05 +08:00
parent 14ef2719c7
commit a5faf21953
6 changed files with 112 additions and 3 deletions

3
apps/next-template/.gitignore vendored Normal file
View file

@ -0,0 +1,3 @@
# clerk configuration (can include secrets)
/.clerk/

View file

@ -12,6 +12,7 @@
"clean": "rm -rf .next"
},
"dependencies": {
"@clerk/nextjs": "^6.22.0",
"@repo/logger": "*",
"@repo/ui": "*",
"next": "^15.3.0",

View file

@ -0,0 +1,23 @@
import {
Card,
CardHeader,
CardTitle,
CardContent,
} from "@repo/ui/components/card";
export default function ClerkTestPage() {
return (
<div className="flex items-center justify-center min-h-screen bg-muted">
<Card className="w-full max-w-md shadow-lg">
<CardHeader>
<CardTitle>Welcome, you are logged in!</CardTitle>
</CardHeader>
<CardContent>
<p className="text-muted-foreground">
This is a protected test page.
</p>
</CardContent>
</Card>
</div>
);
}

View file

@ -1,5 +1,14 @@
import "@repo/ui/styles/styles.css";
import "@repo/ui/styles/global.css";
import {
ClerkProvider,
SignInButton,
SignUpButton,
SignedIn,
SignedOut,
UserButton,
} from "@clerk/nextjs";
import { Button } from "@repo/ui/components/button";
export default function RootLayout({
children,
@ -7,8 +16,24 @@ export default function RootLayout({
children: React.ReactNode;
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
<ClerkProvider>
<html lang="en">
<body>
<header className="flex items-center justify-end py-4 px-6 bg-white shadow-sm mb-6">
<div>
<SignedOut>
<SignInButton mode="modal">
<Button variant="outline">Sign In</Button>
</SignInButton>
</SignedOut>
<SignedIn>
<UserButton afterSignOutUrl="/" />
</SignedIn>
</div>
</header>
{children}
</body>
</html>
</ClerkProvider>
);
}

View file

@ -0,0 +1,28 @@
import { clerkMiddleware, createRouteMatcher } from "@clerk/nextjs/server";
const isProtectedRoute = createRouteMatcher(["/clerk(.*)"]);
export default clerkMiddleware(async (auth, req) => {
// Uncomment the following line to enable Clerk's default behavior | Redirect to sign-in page if the user is not authenticated
// if (isProtectedRoute(req)) await auth.protect();
// More control over authentication flow
const { userId, redirectToSignIn } = await auth();
if (!userId && isProtectedRoute(req)) {
// Add custom logic to run before redirecting
console.log(
"User is not authenticated, redirecting to sign-in page..."
);
return redirectToSignIn();
}
});
export const config = {
matcher: [
// Skip Next.js internals and all static files, unless found in search params
"/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)",
// Always run for API routes
"/(api|trpc)(.*)",
],
};