Deploy to Cloudflare Workers

JSandy can be deployed to Cloudflare Workers, providing a globally distributed, serverless runtime for your API. This guide will walk you through the deployment process.


Prerequisites

  1. Install the Wrangler CLI

    Terminal

    Terminal

    npm install wrangler@latest -g
  2. Make sure you have an account at Cloudflare


Deployment Steps

  1. Deploy your backend to Cloudflare Workers using wrangler deploy. Enter the path to your appRouter file, by default this is:

    Terminal

    Terminal

    wrangler deploy src/server/index.ts

    The console output will look like this:

    Deploy JSandy to Cloudflare Workers
  2. Add the deployment URL to the client:

    TypeScript

    lib/client.ts

    import type { AppRouter } from "@/server"
    import { createClient } from "@jsandy/rpc"
     
    export const client = createClient<AppRouter>({
      baseUrl: `${getBaseUrl()}/api`,
    })
     
    function getBaseUrl() {
      // 👇 In production, use the production worker
      if (process.env.NODE_ENV === "production") {
        return "https://<YOUR_DEPLOYMENT>.workers.dev"
      }
     
      // 👇 Locally, use wrangler backend
      return `http://localhost:8080`
    }

Environment Variables

Make sure your Worker has the necessary environment variables configured. Either enter one at a time or update them in bulk:

Terminal

Terminal

wrangler secret put <KEY>

Production Deployment

When you deploy your front-end application:

  • Deploy to your preferred hosting platform (Vercel, Netlify, etc.)
  • After adding the deployment URL to your lib/client.ts file, your frontend will automatically connect to your Worker

Common Problems

CORS Configuration

If you are experiencing CORS problems, make sure your Worker is configured correctly:

TypeScript

server/index.ts

import { InferRouterInputs, InferRouterOutputs } from "@jsandy/rpc"
import { postRouter } from "./routers/post-router"
import { j } from "./jsandy"
 
const api = j
  .router()
  .basePath("/api")
  .use(j.defaults.cors)
  .onError(j.defaults.errorHandler)
 
const appRouter = j.mergeRouters(api, {
  post: postRouter,
})
 
export type AppRouter = typeof appRouter
 
export default appRouter

→ More about CORS in JSandy