Skip to content

Using Clerk with Cloudflare Workers #1421

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
4 of 20 tasks
Eusebiotrigo opened this issue Jun 27, 2023 · 8 comments
Closed
4 of 20 tasks

Using Clerk with Cloudflare Workers #1421

Eusebiotrigo opened this issue Jun 27, 2023 · 8 comments
Labels
Low priority Created by Linear-GitHub Sync prioritized This issue has been triaged and the team is working on it

Comments

@Eusebiotrigo
Copy link

Eusebiotrigo commented Jun 27, 2023

Package + Version

  • @clerk/clerk-js
  • @clerk/clerk-react
  • @clerk/nextjs
  • @clerk/remix
  • @clerk/types
  • @clerk/themes
  • @clerk/localizations
  • @clerk/clerk-expo
  • @clerk/backend
  • @clerk/clerk-sdk-node
  • @clerk/shared
  • @clerk/fastify
  • @clerk/chrome-extension
  • gatsby-plugin-clerk
  • build/tooling/chore
  • other:

Dependencies + versions

{
  "name": "account",
  "version": "0.0.0",
  "scripts": {
    "start": "wrangler dev",
    "deploy": "wrangler deploy",
    "dry-run": "wrangler deploy --dry-run --outdir=dist",
    "test": "vitest --hideSkippedTests",
    "coverage": "vitest run --coverage",
    "test-report": "vitest run --reporter=junit --outputFile junit-report.xml",
    "lint": "eslint . --ext .ts --fix --max-warnings=0"
  },
  "dependencies": {
    "@clerk/backend": "^0.23.5",
    "@tsndr/cloudflare-worker-jwt": "^2.2.1",
    "hono": "^3.2.6",
    "@xata.io/client": "^0.24.3",
    "uuid": "^9.0.0"
  },
  "devDependencies": {
    "@cloudflare/workers-types": "^4.20230518.0",
    "@types/uuid": "^9.0.2",
    "@typescript-eslint/eslint-plugin": "^5.60.0",
    "@typescript-eslint/parser": "^5.60.0",
    "@vitest/coverage-v8": "^0.32.2",
    "eslint": "8.43.0",
    "typescript": "^5.1.3",
    "vitest": "^0.32.2",
    "vitest-environment-miniflare": "^2.14.0",
    "wrangler": "^3.1.1"
  },
  "private": true
}

Browser/OS

Cloudflare worker 3.1.1

Description

I tried to use @clerk/clerk-sdk-node to interact with Clerk from my cloudflare workers, but due to how the environment variables are declared, using directly process.env, I cannot use it in Cloudflare workers, so I had to use the @clerk/backend.

// src/clerkClient.ts
var API_URL = process.env.CLERK_API_URL || "https://api.clerk.dev";
var API_VERSION = process.env.CLERK_API_VERSION || "v1";
var API_KEY = process.env.CLERK_SECRET_KEY || process.env.CLERK_API_KEY || "";
var PUBLISHABLE_KEY = process.env.CLERK_PUBLISHABLE_KEY || "";
var DOMAIN = process.env.CLERK_DOMAIN || "";
var PROXY_URL = process.env.CLERK_PROXY_URL || "";
var SIGN_IN_URL = process.env.CLERK_SIGN_IN_URL || "";
var IS_SATELLITE = process.env.CLERK_IS_SATELLITE === "true";

I know that Cloudflare is not node.
I could not find any reference to Cloudflare Workers in the documentation.

There is a thread in Discord: https://discord.com/channels/856971667393609759/1105772611511791666

@jamesmcintyre
Copy link

I too am planning on verifying token in cloudflare worker. I've seen another method used in the discord but it'd be nice to see an example repo for this since it's definitely a bit more work: https://discord.com/channels/856971667393609759/1112517462680944640/1112517462680944640

Also are there ways to store small meta-data in that token such as userId so i can make more use of it in the workers environment?

@oliverfunk
Copy link

If you're using Cloudflare Workers, you should use the @clerk/backend package.
See https://github.com/clerkinc/javascript/tree/main/packages/backend

This is how I verified requests on cf workers:

import {
  verifyToken,
} from "@clerk/backend";

export const verifyReqJWT = async (pemString: string, req: Request) => {
  const reqJwtToken = req.headers.get("Authorization");
  if (!reqJwtToken || reqJwtToken === "undefined" || reqJwtToken === "null") {
    return undefined;
  }

  return await verifyToken(reqJwtToken, {
    issuer: "https://<your-identifier>.clerk.accounts.dev",
    jwtKey: pemString,
  });
};

Where you get the pemString from the env var in fetch (env.CLERK_PEM).

Set the CLERK_PEM variable in the .dev.vars file to:

CLERK_PEM="-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----"

It is truly bizarre how bad the docs are on this.

They recommend using the jsonwebtoken package instead of their own, when their own works well.
From https://clerk.com/docs/request-authentication/validate-session-tokens

The implementation of the various functions to get the signed-in context objects etc. are really weird and I spent hours scouring the internet and their code to find out how to do things properly.

There's so little on how to go from a PEM string + a JWT token to a verified JwtPayload.

In an edge function, you don't want to be making additional requests to the .well-known URL, so you want to the PEM string locally.

Anyway, hope that helps.

@Eusebiotrigo
Copy link
Author

Yes, to verify the token and everything I used @tsndr/cloudflare-worker-jwt:

const valid = await jwt.verify(token, c.env.JWT_ACCESS_SIGN_KEY, { algorithm: "RS256" });

And the JWT_ACCESS_SIGN_KEY is the PEM in a string.

@jescalan
Copy link
Contributor

Potential overlap: #1541

@jescalan jescalan added the needs-triage A ticket that needs to be triaged by a team member label Aug 25, 2023
@jescalan jescalan added the linear Created by Linear-GitHub Sync label Nov 16, 2023
@jescalan jescalan added prioritized This issue has been triaged and the team is working on it Low priority Created by Linear-GitHub Sync and removed needs-triage A ticket that needs to be triaged by a team member linear Created by Linear-GitHub Sync labels Nov 27, 2023
@SokratisVidros
Copy link
Contributor

SokratisVidros commented Nov 29, 2023

The NPM @clerk/backend package is an isomorphic package that works in Node and Cloudflare workers.

@dimkl
Copy link
Contributor

dimkl commented Nov 29, 2023

An example of how @clerk/backend can be used can be found:

@Eusebiotrigo
Copy link
Author

We can close this issue then.

@clerk-cookie
Copy link
Collaborator

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@clerk clerk locked as resolved and limited conversation to collaborators Dec 7, 2024
# for free to subscribe to this conversation on GitHub. Already have an account? #.
Labels
Low priority Created by Linear-GitHub Sync prioritized This issue has been triaged and the team is working on it
Projects
None yet
Development

No branches or pull requests

7 participants