Replies: 1 comment 1 reply
-
|
Clerk's official SDKs are tightly coupled to Node.js/React, so there's no drop-in integration for Fresh 2 with Vite. That said, you can absolutely use Clerk with Fresh — you just have to go through their Backend API + JWT verification instead of relying on their framework-specific middleware. Here's the approach that works: 1. Use Clerk's Backend API for session verification in Fresh middleware: // routes/_middleware.ts
import { FreshContext } from "$fresh/server.ts";
import { createRemoteJWKSet, jwtVerify } from "npm:jose";
const CLERK_ISSUER = `https://${Deno.env.get("CLERK_DOMAIN")}`;
const JWKS = createRemoteJWKSet(
new URL(`${CLERK_ISSUER}/.well-known/jwks.json`)
);
export async function handler(req: Request, ctx: FreshContext) {
const sessionToken = getCookie(req.headers, "__session");
if (sessionToken) {
try {
const { payload } = await jwtVerify(sessionToken, JWKS, {
issuer: CLERK_ISSUER,
});
ctx.state.user = payload;
} catch {
// Invalid/expired token — treat as unauthenticated
}
}
return ctx.next();
}2. For the frontend sign-in/sign-up, use Clerk's hosted pages or their JavaScript SDK: Clerk provides // islands/ClerkAuth.tsx
import { useEffect, useRef } from "preact/hooks";
export default function ClerkAuth() {
const mountRef = useRef<HTMLDivElement>(null);
useEffect(() => {
import("npm:@clerk/clerk-js").then(async ({ Clerk }) => {
const clerk = new Clerk("your_publishable_key");
await clerk.load();
if (!clerk.user && mountRef.current) {
clerk.mountSignIn(mountRef.current);
}
});
}, []);
return <div ref={mountRef} />;
}3. Alternatively, just use Clerk's redirect-based flow — point users to your Clerk-hosted sign-in page and handle the callback. This requires zero frontend SDK: // routes/login.ts
export function handler(req: Request) {
return new Response(null, {
status: 302,
headers: {
Location: `https://${Deno.env.get("CLERK_DOMAIN")}/sign-in?redirect_url=${encodeURIComponent(new URL("/dashboard", req.url).toString())}`,
},
});
}The JWT verification approach (option 1) is the most reliable because it doesn't depend on any framework-specific Clerk package — just standard JWKS verification, which works everywhere. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Clerk is a THE most popular auth tool for modern TS frontends.
I tried to find at least one Fresh 2 public repo on Github using it but could not find it.
There is a Clerk plugin (@jsrob/fresh-clerk) but it works for alpha Fresh 2 only, unfortunately. Not for Fresh 2 with vite support.
Can somebody point me to any Fresh 2 project using Clerk?
Beta Was this translation helpful? Give feedback.
All reactions