|
| 1 | +import type { AppLoadContext, ServerBuild } from 'react-router' |
| 2 | +import { |
| 3 | + createContext, |
| 4 | + RouterContextProvider, |
| 5 | + createRequestHandler as createReactRouterRequestHandler, |
| 6 | +} from 'react-router' |
| 7 | +import type { Context as NetlifyEdgeContext } from '@netlify/edge-functions' |
| 8 | + |
| 9 | +// Augment the user's `AppLoadContext` to include Netlify context fields |
| 10 | +// This is the recommended approach: https://reactrouter.com/upgrading/remix#9-update-types-for-apploadcontext. |
| 11 | +declare module 'react-router' { |
| 12 | + interface AppLoadContext extends NetlifyEdgeContext {} |
| 13 | +} |
| 14 | + |
| 15 | +/** |
| 16 | + * A function that returns the value to use as `context` in route `loader` and `action` functions. |
| 17 | + * |
| 18 | + * You can think of this as an escape hatch that allows you to pass environment/platform-specific |
| 19 | + * values through to your loader/action. |
| 20 | + * |
| 21 | + * NOTE: v7.9.0 introduced a breaking change when the user opts in to `future.v8_middleware`. This |
| 22 | + * requires returning an instance of `RouterContextProvider` instead of a plain object. We have a |
| 23 | + * peer dependency on >=7.9.0 so we can safely *import* these, but we cannot assume the user has |
| 24 | + * opted in to the flag. |
| 25 | + */ |
| 26 | +export type GetLoadContextFunction = GetLoadContextFunction_V7 | GetLoadContextFunction_V8 |
| 27 | +export type GetLoadContextFunction_V7 = ( |
| 28 | + request: Request, |
| 29 | + context: NetlifyEdgeContext, |
| 30 | +) => Promise<AppLoadContext> | AppLoadContext |
| 31 | +export type GetLoadContextFunction_V8 = ( |
| 32 | + request: Request, |
| 33 | + context: NetlifyEdgeContext, |
| 34 | +) => Promise<RouterContextProvider> | RouterContextProvider |
| 35 | + |
| 36 | +export type RequestHandler = (request: Request, context: NetlifyEdgeContext) => Promise<Response> |
| 37 | + |
| 38 | +/** |
| 39 | + * An instance of `ReactContextProvider` providing access to |
| 40 | + * [Netlify request context]{@link https://docs.netlify.com/build/functions/api/#netlify-specific-context-object} |
| 41 | + * |
| 42 | + * @example context.get(netlifyRouterContext).geo?.country?.name |
| 43 | + */ |
| 44 | +export const netlifyRouterContext = |
| 45 | + // We must use a singleton because Remix contexts rely on referential equality. |
| 46 | + // We can't hook into the request lifecycle in dev mode, so we use a Proxy to always read from the |
| 47 | + // current `Netlify.context` value, which is always contextual to the in-flight request. |
| 48 | + createContext<Partial<NetlifyEdgeContext>>( |
| 49 | + new Proxy( |
| 50 | + // Can't reference `Netlify.context` here because it isn't set outside of a request lifecycle |
| 51 | + {}, |
| 52 | + { |
| 53 | + get(_target, prop, receiver) { |
| 54 | + return Reflect.get(Netlify.context ?? {}, prop, receiver) |
| 55 | + }, |
| 56 | + set(_target, prop, value, receiver) { |
| 57 | + return Reflect.set(Netlify.context ?? {}, prop, value, receiver) |
| 58 | + }, |
| 59 | + has(_target, prop) { |
| 60 | + return Reflect.has(Netlify.context ?? {}, prop) |
| 61 | + }, |
| 62 | + deleteProperty(_target, prop) { |
| 63 | + return Reflect.deleteProperty(Netlify.context ?? {}, prop) |
| 64 | + }, |
| 65 | + ownKeys(_target) { |
| 66 | + return Reflect.ownKeys(Netlify.context ?? {}) |
| 67 | + }, |
| 68 | + getOwnPropertyDescriptor(_target, prop) { |
| 69 | + return Reflect.getOwnPropertyDescriptor(Netlify.context ?? {}, prop) |
| 70 | + }, |
| 71 | + }, |
| 72 | + ), |
| 73 | + ) |
| 74 | + |
| 75 | +/** |
| 76 | + * Given a build and a callback to get the base loader context, this returns |
| 77 | + * a Netlify Edge Function handler (https://docs.netlify.com/edge-functions/overview/) which renders the |
| 78 | + * requested path. The loader context in this lifecycle will contain the Netlify Edge Functions context |
| 79 | + * fields merged in. |
| 80 | + */ |
| 81 | +export function createRequestHandler({ |
| 82 | + build, |
| 83 | + mode, |
| 84 | + getLoadContext, |
| 85 | +}: { |
| 86 | + build: ServerBuild |
| 87 | + mode?: string |
| 88 | + getLoadContext?: GetLoadContextFunction |
| 89 | +}): RequestHandler { |
| 90 | + const reactRouterHandler = createReactRouterRequestHandler(build, mode) |
| 91 | + |
| 92 | + return async (request: Request, netlifyContext: NetlifyEdgeContext): Promise<Response> => { |
| 93 | + const start = Date.now() |
| 94 | + console.log(`[${request.method}] ${request.url}`) |
| 95 | + try { |
| 96 | + const getDefaultReactRouterContext = () => { |
| 97 | + const ctx = new RouterContextProvider() |
| 98 | + ctx.set(netlifyRouterContext, netlifyContext) |
| 99 | + |
| 100 | + // Provide backwards compatibility with previous plain object context |
| 101 | + // See https://reactrouter.com/how-to/middleware#migration-from-apploadcontext. |
| 102 | + Object.assign(ctx, netlifyContext) |
| 103 | + |
| 104 | + return ctx |
| 105 | + } |
| 106 | + const reactRouterContext = (await getLoadContext?.(request, netlifyContext)) ?? getDefaultReactRouterContext() |
| 107 | + |
| 108 | + // @ts-expect-error -- I don't think there's any way to type this properly. We're passing a |
| 109 | + // union of the two types here, but this function accepts a conditional type based on the |
| 110 | + // presence of the `future.v8_middleware` flag in the user's config, which we don't have access to. |
| 111 | + const response = await reactRouterHandler(request, reactRouterContext) |
| 112 | + |
| 113 | + // We can return any React Router response as-is (whether it's a default 404, custom 404, |
| 114 | + // or any other response) because our edge function's excludedPath config is exhaustive - |
| 115 | + // static assets are excluded from the edge function entirely, so we never need to fall |
| 116 | + // through to the CDN. |
| 117 | + console.log(`[${response.status}] ${request.url} (${Date.now() - start}ms)`) |
| 118 | + return response |
| 119 | + } catch (error) { |
| 120 | + console.error(error) |
| 121 | + |
| 122 | + return new Response('Internal Error', { status: 500 }) |
| 123 | + } |
| 124 | + } |
| 125 | +} |
0 commit comments