@@ -35,20 +35,44 @@ export type GetLoadContextFunction_V8 = (
3535
3636export type RequestHandler = ( request : Request , context : NetlifyContext ) => Promise < Response >
3737
38- let netlifyRouterContext : RouterContext < Partial < NetlifyContext > >
3938/**
4039 * An instance of `ReactContextProvider` providing access to
4140 * [Netlify request context]{@link https://docs.netlify.com/build/functions/api/#netlify-specific-context-object}
4241 *
43- * @example context.get(getNetlifyRouterContext() ).geo?.country?.name
42+ * @example context.get(netlifyRouterContext ).geo?.country?.name
4443 */
45- export const getNetlifyRouterContext = ( ) => {
46- // We must use a singleton because Remix contexts rely on referential equality
44+ export const netlifyRouterContext =
45+ // We must use a singleton because Remix contexts rely on referential equality.
4746 // We defer initialization until first use so that we can initialize it with a default value
48- // within a request lifecycle, where the `Netlify` global will be set. This is just for dev.
49- netlifyRouterContext ??= createContext < Partial < NetlifyContext > > ( Netlify . context ?? { } )
50- return netlifyRouterContext
51- }
47+ // within a request lifecycle, where the `Netlify` global will be set.
48+ // Finally, because we can't hook into the request lifecycle in dev mode, we use a Proxy to always read from the current
49+ // `Netlify.context` value, which is always contextual to the in-flight request.
50+ createContext < Partial < NetlifyContext > > (
51+ new Proxy (
52+ // Can't reference `Netlify.context` here because it isn't set outside of a request lifecycle
53+ { } ,
54+ {
55+ get ( _target , prop , receiver ) {
56+ return Reflect . get ( Netlify . context ?? { } , prop , receiver )
57+ } ,
58+ set ( _target , prop , value , receiver ) {
59+ return Reflect . set ( Netlify . context ?? { } , prop , value , receiver )
60+ } ,
61+ has ( _target , prop ) {
62+ return Reflect . has ( Netlify . context ?? { } , prop )
63+ } ,
64+ deleteProperty ( _target , prop ) {
65+ return Reflect . deleteProperty ( Netlify . context ?? { } , prop )
66+ } ,
67+ ownKeys ( _target ) {
68+ return Reflect . ownKeys ( Netlify . context ?? { } )
69+ } ,
70+ getOwnPropertyDescriptor ( _target , prop ) {
71+ return Reflect . getOwnPropertyDescriptor ( Netlify . context ?? { } , prop )
72+ } ,
73+ } ,
74+ ) ,
75+ )
5276
5377/**
5478 * Given a build and a callback to get the base loader context, this returns
@@ -73,7 +97,7 @@ export function createRequestHandler({
7397 try {
7498 const getDefaultReactRouterContext = ( ) => {
7599 const ctx = new RouterContextProvider ( )
76- ctx . set ( getNetlifyRouterContext ( ) , netlifyContext )
100+ ctx . set ( netlifyRouterContext , netlifyContext )
77101
78102 // Provide backwards compatibility with previous plain object context
79103 // See https://reactrouter.com/how-to/middleware#migration-from-apploadcontext.
0 commit comments