Blog

Launch Week Day 4: Cloudflare Workers & Edge support

The workos-node library now supports JavaScript environments like Deno, Bun, Cloudflare Workers, Vercel, and Node, simplifying API requests across these platforms.


The workos-node library now supports additional JavaScript environments like Deno, Bun, Cloudflare Workers, Vercel, and of course Node.js. Instead of having to make your own API calls in environments that don’t support older HTTP request libraries, you can now use our SDK to easily make the requests you need to the WorkOS API.

To use workos-node in Cloudflare Workers and Edge Middleware, simply update to the latest version.

Let’s see how this works in just a few samples. First, here’s how sessions would work using middleware on Next.js:

      
import { NextRequest, NextResponse } from "next/server";
import { cookies } from "next/headers";
import WorkOS from "@workos-inc/node";
import { sealData } from "iron-session";

const workos = new WorkOS(process.env.WORKOS_API_KEY);

export async function middleware(request: NextRequest) {
  // Get code from the URL
  const code: string = request.nextUrl.searchParams.get("code") as string;

  // Get the user from the WorkOS API
  const { user, accessToken, refreshToken } =
    await workos.userManagement.authenticateWithCode({
      clientId: process.env.WORKOS_CLIENT_ID as string,
      code,
    });

  // Store the user, access and refresh tokens
  // Refresh tokens should only be stored in a cookie if the cookie is encrypted,
  // otherwise they should be persisted in a backend database
  cookies().set(
    "workos-session",
    await sealData(
      { accessToken, refreshToken, user }, 
      { password: process.env.COOKIE_PASSWORD }
    ),
    {
      path: "/",
      httpOnly: true,
      secure: true,
      sameSite: "lax",
    }
  );


  const url = request.nextUrl.clone();

  // Cleanup params
  url.searchParams.delete("code");
  url.pathname = "/";

  return NextResponse.redirect(url);
}

// Match against the callback URI
export const config = { matcher: ["/callback"] };
        
      

In the example above, the user has gone through the AuthKit login flow and has been redirected to the callback URL. The middleware extracts the code embedded in the URL by the WorkOS API and fetches the user object by authenticating with the Node SDK. The resulting data is then stored in a session before redirecting the user.

Alternatively, the above can automatically be handled for you by using our Next.js library, which also handles using refresh tokens to generate new access tokens for session management.

Sessions are a new feature in WorkOS. Released just a few days ago, they enable easy-to-use, secure session management in your app. Now made even easier by enabling the use of workos-node in Edge runtime environments like Next.js middleware.

Next, here’s a simple Cloudflare Worker for processing a webhook event sent by the WorkOS API:

      
import { Router } from 'itty-router';
import WorkOS from '@workos-inc/node';

// Create a new router
const router = Router();

router.post('/webhook', async (request, env) => {
  // Initialize WorkOS
  const workos = new WorkOS(env.WORKOS_API_KEY);

  let event;

  try {
    // Construct the webhook event
    event = await workos.webhooks.constructEvent({
      payload: await request.json(),
      sigHeader: request.headers.get('WorkOS-Signature'),
      secret: env.WEBHOOK_SECRET,
    });
  } catch (e) {
    return new Response('403, webhook event failed', { status: 403 });
  }

  // Send event to message queue...

  // Return a success state early to acknowledge receipt of the event
  return new Response('ok', { status: 200 });
});

export default {
  fetch: (req, env) => router.handle(req, env),
};
        
      

Above we use `itty-router` to route our callback URL, where we use the WorkOS signature and webhook signing secret to decrypt the webhook event. 

These are just two examples of how you can use workos-node today. With these improvements, WorkOS products such as AuthKit can now run in many alternative JavaScript runtimes such as Deno or Bun.

Modern infrastructure like Cloudflare Workers and AuthKit are easy to use and powerful, imagine what you can build when you combine these together to supercharge your applications.

How it works

In order to make workos-node compatible with modern JavaScript runtimes, we had to upgrade two core dependencies:

  1. Using the Fetch API rather than Node’s `http` library
  2. Using the Web Crypto API instead of Node’s `crypto` package

One of the benefits of both `fetch` and the Web Crypto API (a.k.a `sublteCrypto`) is that they are designed to be used isomorphically, meaning that they utilize the same API whether they are used in a browser or server environment. As both are standardized JavaScript libraries, using them means having a certain degree of future proofing should new JavaScript runtimes arise and grow in popularity.

That concludes day four of Launch Week. Tune in tomorrow to see how we are equipping support teams with better tooling to help your users.

In this article

This site uses cookies to improve your experience. Please accept the use of cookies on this site. You can review our cookie policy here and our privacy policy here. If you choose to refuse, functionality of this site will be limited.