本页还没有译文
本页 76 段还没译成日本語,下面显示的是英文原文。React + Vite
还没翻译译自英文(developers.cloudflare.com)本页 76 段都还没译
React is a framework for building user interfaces. It allows you to create reusable UI components and manage the state of your application efficiently. You can use React to build a single-page application (SPA), and combine it with a backend API running on Cloudflare Workers to create a full-stack application.
This guide shows you how to deploy a React + Vite application to Cloudflare Workers. You can either create a new project using the create-cloudflare CLI (C3) or adapt an existing React + Vite project.
Start from CLI - scaffold a full-stack app with a React SPA, Cloudflare Workers API, and the Cloudflare Vite plugin for lightning-fast development.
npm create cloudflare@latest -- my-react-app --framework=reactyarn create cloudflare my-react-app --framework=reactpnpm create cloudflare@latest my-react-app --framework=reactOr just deploy - create a full-stack app using React, a Workers API, and Vite, with CI/CD and previews all set up for you.
-
Create a new project with the create-cloudflare CLI (C3)
npm create cloudflare@latest -- my-react-app --framework=reactyarn create cloudflare my-react-app --framework=reactpnpm create cloudflare@latest my-react-app --framework=reactHow is this project set up?
The following is a simplified file tree of the project.
my-react-app
src/
- App.tsx
worker/
- index.ts
- index.html
- vite.config.ts
- wrangler.jsonc
wrangler.jsoncis your Wrangler configuration file. In this file:mainpoints toworker/index.ts. This is your Worker, which is going to act as your backend API.assets.not_found_handlingis set tosingle-page-application, which means that routes that are handled by your React SPA do not go to the Worker, and are thus free.- If you want to add bindings to resources on Cloudflare's developer platform, you configure them here. Read more about bindings.
vite.config.tsis set up to use the Cloudflare Vite plugin. This runs your Worker in the Cloudflare Workers runtime, ensuring your local development environment is as close to production as possible.worker/index.tsis your backend API, which contains a single endpoint,/api/, that returns a text response. Atsrc/App.tsx, your React app calls this endpoint to get a message back and displays this. -
Develop locally with the Cloudflare Vite plugin
After creating your project, run the following command in your project directory to start a local development server.
npm run devyarn run devpnpm run devWhat's happening in local development?
This project uses Vite for local development and build, and thus comes with all of Vite's features, including hot module replacement (HMR).
In addition,
vite.config.tsis set up to use the Cloudflare Vite plugin. This runs your application in the Cloudflare Workers runtime, just like in production, and enables access to local emulations of bindings. -
Deploy your project
Your project can be deployed to a
*.workers.devsubdomain or a Custom Domain, from your own machine or from any CI/CD system, including Cloudflare's own Workers Builds.The following command will build and deploy your project. If you are using CI, ensure you update your "deploy command" configuration appropriately.
npm run deployyarn run deploypnpm run deploy
If you already have a React + Vite application, you can adapt it to deploy to Cloudflare Workers using the Cloudflare Vite plugin. This approach preserves your existing code while adding the ability to deploy to Cloudflare's edge network with static assets and an optional API Worker.
-
Navigate to your project directory
Open your existing React + Vite project in your editor of choice. If you do not have one yet, scaffold a new project with Vite first:
npm create vite@latest -- my-react-app --template react-tsyarn create vite my-react-app --template react-tspnpm create vite@latest my-react-app --template react-tsNext, open the
my-react-appdirectory in your editor of choice. -
Add the Cloudflare Vite plugin
Add the Cloudflare dependencies
npm i -D @cloudflare/vite-plugin wrangleryarn add -D @cloudflare/vite-plugin wranglerpnpm add -D @cloudflare/vite-plugin wranglerbun add -d @cloudflare/vite-plugin wranglerAdd the Cloudflare Vite plugin to your project
In your
vite.config.ts, add the Cloudflare Vite plugin after your framework plugin:vite.config.tsimport { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import { cloudflare } from "@cloudflare/vite-plugin"; export default defineConfig({ plugins: [react(), cloudflare({ viteEnvironment: { name: "worker" } })], environments: { worker: { build: { sourcemap: true } }, }, });The Cloudflare Vite plugin looks for a
wrangler.jsonc,wrangler.json, orwrangler.tomlin the root of your application.The
workerenvironment generates source maps for your Worker. The client environment keeps its existing source map settings.Refer to the API reference for configuration options.
-
Add a Wrangler configuration file
Create your Worker config file
Create a
wrangler.jsoncfile in the root of your project:{ "$schema": "./node_modules/wrangler/config-schema.json", "name": "my-app", // Set this to today's date "compatibility_date": "2026-11-02", "assets": { "not_found_handling": "single-page-application" } }name = "my-app" # Set this to today's date compatibility_date = "2026-11-02" [assets] not_found_handling = "single-page-application"The
not_found_handlingvalue has been set tosingle-page-application. This means that all not-found requests will serve theindex.htmlfile, which is required for React Router and other client-side routing solutions.With the Cloudflare plugin, the
assetsrouting configuration is used in place of Vite's default behavior. This ensures that your application's routing configuration works the same way while developing as it does when deployed to production.The
directoryfield is not used when configuring assets with Vite. Thedirectoryin the output configuration will automatically point to the client build output. Refer to Static Assets for more information.Note
When using the Cloudflare Vite plugin, the Worker config (for example,
wrangler.jsonc) that you provide is the input configuration file. A separate outputwrangler.jsonfile is created when you runvite build. This output file is a snapshot of your configuration at the time of the build and is modified to reference your build artifacts. It is the configuration that is used for preview and deployment. -
Update the
.gitignorefileUpdate the
.gitignorefileWhen developing Workers, additional files are used and/or generated that should not be stored in Git. Add the following lines to your
.gitignorefile:.gitignore.wrangler .dev.vars* -
Develop locally
Run the development server
Run your framework's development command to start the Vite development server and verify that your application is working as expected.
npm run devyarn run devpnpm run devFor a purely front-end application, you could now build, preview, and deploy your application. The following sections will show you how to go further and add an API Worker.
-
Build and deploy your project
Build your application
Run the build command to build your application.
npm run buildyarn run buildpnpm run buildThe
distdirectory will contain your client build output in theclientsubdirectory and your Worker code alongside the outputwrangler.jsonconfiguration file.Preview your application
Run the preview command to validate that your application runs as expected.
npm run previewyarn run previewpnpm run previewThis command will run your build output locally in the Workers runtime, closely matching its behavior in production.
Deploy to Cloudflare
Run the deploy command to deploy your application to Cloudflare.
npx wrangler deployyarn wrangler deploypnpm wrangler deployThis command will automatically use the output
wrangler.jsonthat was included in the build output.
Add an API Worker to an existing project
If you want to add an API Worker to your existing React + Vite project, follow these additional steps:
-
Configure TypeScript for your Worker code
Add Workers TypeScript types
npm i -D @cloudflare/workers-typesyarn add -D @cloudflare/workers-typespnpm add -D @cloudflare/workers-typesbun add -d @cloudflare/workers-typesCreate a
tsconfig.worker.jsonthat extends your Node TypeScript configuration and adds the Workers types:tsconfig.worker.json{ "extends": "./tsconfig.node.json", "compilerOptions": { "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.worker.tsbuildinfo", "types": ["@cloudflare/workers-types/2023-07-01", "vite/client"], }, "include": ["worker"], }Then add a reference to this new configuration in your root
tsconfig.json:tsconfig.json{ "files": [], "references": [ { "path": "./tsconfig.app.json" }, { "path": "./tsconfig.node.json" }, { "path": "./tsconfig.worker.json" }, ], } -
Add the Worker entrypoint to your configuration
Add the Worker entrypoint to your configuration
Update your Wrangler configuration file to add a
mainfield that points to your Worker entrypoint:{ "$schema": "./node_modules/wrangler/config-schema.json", "name": "my-app", // Set this to today's date "compatibility_date": "2026-11-02", "main": "./worker/index.ts", "upload_source_maps": true, "assets": { "not_found_handling": "single-page-application" } }name = "my-app" # Set this to today's date compatibility_date = "2026-11-02" main = "./worker/index.ts" upload_source_maps = true [assets] not_found_handling = "single-page-application"The
mainfield specifies the entry file for your Worker code. -
Add your API Worker
Add your API Worker
Create a
worker/index.tsfile with the following contents:worker/index.tsexport default { fetch(request) { const url = new URL(request.url); if (url.pathname.startsWith("/api/")) { return Response.json({ name: "Cloudflare", }); } return new Response(null, { status: 404 }); }, } satisfies ExportedHandler;The Worker defined in the preceding code block will be invoked for any non-navigation request that does not match a static asset. It returns a JSON response if the
pathnamestarts with/api/and otherwise returns a404response.Note
For top-level navigation requests, browsers send a
Sec-Fetch-Mode: navigateheader. If this is present and the URL does not match a static asset, thenot_found_handlingbehavior will be invoked rather than the Worker. This implicit routing is the default behavior.If you would instead like to define the routes that invoke your Worker explicitly, you can provide an array of route patterns to
run_worker_first. This opts out of interpreting theSec-Fetch-Modeheader.{ "$schema": "./node_modules/wrangler/config-schema.json", "name": "cloudflare-vite-tutorial", // Set this to today's date "compatibility_date": "2026-11-02", "main": "./worker/index.ts", "upload_source_maps": true, "assets": { "not_found_handling": "single-page-application", "run_worker_first": [ "/api/*" ] } }name = "cloudflare-vite-tutorial" # Set this to today's date compatibility_date = "2026-11-02" main = "./worker/index.ts" upload_source_maps = true [assets] not_found_handling = "single-page-application" run_worker_first = ["/api/*"] -
Call the API from the client
You can now call your API from your React components. For example, in
src/App.tsx:src/App.tsximport { useState } from "react"; function App() { const [name, setName] = useState("unknown"); return ( <div className="card"> <button onClick={() => { fetch("/api/") .then((res) => res.json() as Promise<{ name: string }>) .then((data) => setName(data.name)); }} > Name from API is: {name} </button> </div> ); } export default App;
Asset Routing
If you're using React as a SPA, you will want to set not_found_handling = "single-page-application" in your Wrangler configuration file.
By default, Cloudflare first tries to match a request path against a static asset path, which is based on the file structure of the uploaded asset directory. This is either the directory specified by assets.directory in your Wrangler config or, in the case of the Cloudflare Vite plugin, the output directory of the client build. Failing that, we invoke a Worker if one is present. If there is no Worker, or the Worker then uses the asset binding, Cloudflare will fallback to the behaviour set by not_found_handling.
Refer to the routing documentation for more information about how routing works with static assets, and how to customize this behavior.
Use bindings with React
Your project can also contain a Worker at ./worker/index.ts, which you can use as a backend API for your React application. While your React application cannot directly access Workers bindings, it can interact with them through this Worker. You can make fetch() requests from your React application to the Worker, which can then handle the request and use bindings. Learn how to configure Workers bindings.
With bindings, your application can be fully integrated with the Cloudflare Developer Platform, giving you access to compute, storage, AI and more.