Skip to content

feat: add @netlify/vite-plugin-react-router to support React Router 7 #472

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,6 @@ build/

# Generated by `deno types`
/packages/remix-edge-adapter/deno.d.ts

# React Router
.react-router/
7 changes: 6 additions & 1 deletion .release-please-manifest.json
Original file line number Diff line number Diff line change
@@ -1 +1,6 @@
{"packages/remix-edge-adapter":"3.4.2","packages/remix-runtime":"2.3.1","packages/remix-adapter":"2.5.1"}
{
"packages/remix-edge-adapter": "3.4.2",
"packages/remix-runtime": "2.3.1",
"packages/remix-adapter": "2.5.1",
"packages/vite-plugin-react-router": "0.0.0"
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"p-limit": "^5.0.0",
"prettier": "^3.0.0",
"typescript": "^5.0.0",
"vitest": "^1.0.0"
"vitest": "^2.1.8"
},
"dependencies": {
"@netlify/edge-functions": "^2.10.0",
Expand Down
4 changes: 1 addition & 3 deletions packages/remix-adapter/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,12 @@
"@remix-run/react": "^2.12.0",
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"lambda-tester": "^4.0.1",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this was unused

"react": "^18.2.0",
"react-dom": "^18.2.0",
"tsup": "^8.0.2",
"vite": "^5.1.3"
"vite": "^5.4.11"
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to upgrade this to resolve some type issues caused by having multiple versions of vite in the workspace.

},
"peerDependencies": {
"@netlify/functions": "^2.8.1",
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this was ever relevant, or at least it isn't currently

"vite": "^5.0.0"
},
"peerDependenciesMeta": {
Expand Down
1 change: 1 addition & 0 deletions packages/vite-plugin-react-router/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# Changelog
16 changes: 16 additions & 0 deletions packages/vite-plugin-react-router/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
MIT License

Copyright (c) Netlify Inc. 2024

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or
substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 changes: 29 additions & 0 deletions packages/vite-plugin-react-router/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# React Router Adapter for Netlify

The React Router Adapter for Netlify allows you to deploy your [React Router](https://reactrouter.com) app to
[Netlify Functions](https://docs.netlify.com/functions/overview/).

To deploy a React Router 7+ site to Netlify, install this package:

## How to use

```sh
npm --save-dev install @netlify/vite-plugin-react-router
```

and include the Netlify plugin in your `vite.config.ts`:

```typescript
import { reactRouter } from '@react-router/dev/vite'
import { defineConfig } from 'vite'
import tsconfigPaths from 'vite-tsconfig-paths'
import netlifyPlugin from '@netlify/vite-plugin-react-router' // <- add this

export default defineConfig({
plugins: [
reactRouter(),
tsconfigPaths(),
netlifyPlugin(), // <- add this
],
})
```
70 changes: 70 additions & 0 deletions packages/vite-plugin-react-router/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
{
"name": "@netlify/vite-plugin-react-router",
"version": "0.0.0",
"description": "React Router 7+ Vite plugin for Netlify",
"type": "commonjs",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"exports": {
".": {
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
}
}
},
"files": [
"dist/**/*",
"LICENSE",
"README.md",
"CHANGELOG.md"
],
"scripts": {
"prepack": "pnpm run build",
"build": "tsup-node src/index.ts --format esm,cjs --dts --target node18 --clean",
"build:watch": "pnpm run build --watch"
},
"repository": {
"type": "git",
"url": "https://github.com/netlify/remix-compute",
"directory": "packages/vite-plugin-react-router"
},
"keywords": [
"react-router",
"vite-plugin",
"netlify"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/netlify/remix-compute/issues"
},
"homepage": "https://github.com/netlify/remix-compute#readme",
"dependencies": {
"@react-router/node": "^7.0.1",
"isbot": "^5.0.0",
"react-router": "^7.0.1"
},
"devDependencies": {
"@netlify/functions": "^2.8.1",
"@types/react": "^18.0.27",
"@types/react-dom": "^18.0.10",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"tsup": "^8.0.2",
"vite": "^5.4.11"
},
"peerDependencies": {
"vite": ">=5.0.0"
},
"engines": {
"node": ">=18"
},
"publishConfig": {
"access": "public"
}
}
4 changes: 4 additions & 0 deletions packages/vite-plugin-react-router/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export type { GetLoadContextFunction, RequestHandler } from './server'
export { createRequestHandler } from './server'

export { netlifyPlugin as default } from './plugin'
100 changes: 100 additions & 0 deletions packages/vite-plugin-react-router/src/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import type { Plugin, ResolvedConfig } from 'vite'
import { mkdir, writeFile } from 'node:fs/promises'
import { join, relative, sep } from 'node:path'
import { sep as posixSep } from 'node:path/posix'
import { version, name } from '../package.json'

// https://docs.netlify.com/frameworks-api/#netlify-v1-functions
const NETLIFY_FUNCTIONS_DIR = '.netlify/v1/functions'

const FUNCTION_FILENAME = 'react-router-server.mjs'
/**
* The chunk filename without an extension, i.e. in the Rollup config `input` format
*/
const FUNCTION_HANDLER_CHUNK = 'server'

const FUNCTION_HANDLER_MODULE_ID = 'virtual:netlify-server'
const RESOLVED_FUNCTION_HANDLER_MODULE_ID = `\0${FUNCTION_HANDLER_MODULE_ID}`

const toPosixPath = (path: string) => path.split(sep).join(posixSep)

// The virtual module that is the compiled Vite SSR entrypoint (a Netlify Function handler)
const FUNCTION_HANDLER = /* js */ `
import { createRequestHandler } from "@netlify/vite-plugin-react-router";
import * as build from "virtual:react-router/server-build";
export default createRequestHandler({
build,
getLoadContext: async (_req, ctx) => ctx,
});
`

// This is written to the functions directory. It just re-exports
// the compiled entrypoint, along with Netlify function config.
function generateNetlifyFunction(handlerPath: string) {
return /* js */ `
export { default } from "${handlerPath}";

export const config = {
name: "React Router server handler",
generator: "${name}@${version}",
path: "/*",
preferStatic: true,
};
`
}

export function netlifyPlugin(): Plugin {
let resolvedConfig: ResolvedConfig
let isProductionSsrBuild = false
return {
name: 'vite-plugin-netlify-react-router',
config(config, { command, isSsrBuild }) {
isProductionSsrBuild = isSsrBuild === true && command === 'build'
if (isProductionSsrBuild) {
// Replace the default SSR entrypoint with our own entrypoint (which is imported by our
// Netlify function handler via a virtual module)
config.build ??= {}
config.build.rollupOptions ??= {}
config.build.rollupOptions.input = {
[FUNCTION_HANDLER_CHUNK]: FUNCTION_HANDLER_MODULE_ID,
}
config.build.rollupOptions.output ??= {}
if (Array.isArray(config.build.rollupOptions.output)) {
console.warn(
'Expected Vite config `build.rollupOptions.output` to be an object, but it is an array - overwriting it, but this may cause issues with your custom configuration',
)
config.build.rollupOptions.output = {}
}
config.build.rollupOptions.output.entryFileNames = '[name].js'
}
},
async resolveId(source) {
if (source === FUNCTION_HANDLER_MODULE_ID) {
return RESOLVED_FUNCTION_HANDLER_MODULE_ID
}
},
// See https://vitejs.dev/guide/api-plugin#virtual-modules-convention.
load(id) {
if (id === RESOLVED_FUNCTION_HANDLER_MODULE_ID) {
return FUNCTION_HANDLER
}
},
async configResolved(config) {
resolvedConfig = config
},
// See https://rollupjs.org/plugin-development/#writebundle.
async writeBundle() {
// Write the server entrypoint to the Netlify functions directory
if (isProductionSsrBuild) {
const functionsDirectory = join(resolvedConfig.root, NETLIFY_FUNCTIONS_DIR)

await mkdir(functionsDirectory, { recursive: true })

const handlerPath = join(resolvedConfig.build.outDir, `${FUNCTION_HANDLER_CHUNK}.js`)
const relativeHandlerPath = toPosixPath(relative(functionsDirectory, handlerPath))

await writeFile(join(functionsDirectory, FUNCTION_FILENAME), generateNetlifyFunction(relativeHandlerPath))
}
},
}
}
53 changes: 53 additions & 0 deletions packages/vite-plugin-react-router/src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import type { AppLoadContext, ServerBuild } from 'react-router'
import { createRequestHandler as createReactRouterRequestHandler } from 'react-router'
import type { Context as NetlifyContext } from '@netlify/functions'

type LoadContext = AppLoadContext & NetlifyContext

/**
* A function that returns the value to use as `context` in route `loader` and
* `action` functions.
*
* You can think of this as an escape hatch that allows you to pass
* environment/platform-specific values through to your loader/action.
*/
export type GetLoadContextFunction = (request: Request, context: NetlifyContext) => Promise<LoadContext> | LoadContext

export type RequestHandler = (request: Request, context: LoadContext) => Promise<Response | void>

/**
* Given a build and a callback to get the base loader context, this returns
* a Netlify Function handler (https://docs.netlify.com/functions/overview/) which renders the
* requested path. The loader context in this lifecycle will contain the Netlify Functions context
* fields merged in.
*/
export function createRequestHandler({
build,
mode,
getLoadContext,
}: {
build: ServerBuild
mode?: string
getLoadContext?: GetLoadContextFunction
}): RequestHandler {
const reactRouterHandler = createReactRouterRequestHandler(build, mode)

return async (request: Request, netlifyContext: NetlifyContext): Promise<Response | void> => {
const start = Date.now()
console.log(`[${request.method}] ${request.url}`)
try {
const mergedLoadContext = (await getLoadContext?.(request, netlifyContext)) || netlifyContext

const response = await reactRouterHandler(request, mergedLoadContext)

// A useful header for debugging
response.headers.set('x-nf-runtime', 'Node')
console.log(`[${response.status}] ${request.url} (${Date.now() - start}ms)`)
return response
} catch (error) {
console.error(error)

return new Response('Internal Error', { status: 500 })
}
}
}
9 changes: 9 additions & 0 deletions packages/vite-plugin-react-router/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"rootDir": "src",
"jsx": "react-jsx",
"outDir": "./build"
},
"include": ["./src"]
}
12 changes: 12 additions & 0 deletions packages/vite-plugin-react-router/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/// <reference types="vitest" />
/// <reference types="vite/client" />

import { defineProject } from 'vitest/config'

export default defineProject({
plugins: [],
test: {
include: ['./__tests__/*.{js,jsx,tsx,ts}'],
globals: true,
},
})
Loading
Loading