#createRequestHandler context from @react-router/express

1 messages · Page 1 of 1 (latest)

celest pebble
#

Hello! I'm trying to figure out how to access load context in my loader with the new Map api in getLoadContext.

export const serverBuildContext = createContext<ReturnType<typeof getBuild>>()

app.all(
  '*',
  createRequestHandler({
    getLoadContext() {
      const context = new RouterContextProvider()
      context.set(serverBuildContext, getBuild())
      return context
    },
...

I can't import serverBuildContext in my route and vice versa because build fails with no import found, so not sure where to put router contexts to be able to access them from my app? I'm building sitemap.xml from my loader and it used to work with older api where I didn't need to depend on imports

export async function loader({request, context}: LoaderFunctionArgs) {
const serverBuild = await context.get(serverBuildContext)

any ideas? Thanks!

normal vapor
#

try moving this to a dedicated file that gets imported to use in the getLoadContext and in your loaders

// ~/context/server-build-context.server.ts
export const serverBuildContext = createContext<ReturnType<typeof getBuild>>()
turbid glen
#
export type ServerBuild = ReturnType<typeof getBuild>;

declare module "react-router" {
  export interface Future {
    v8_middleware: true;
  }
  export interface RouterContextProvider {
    readonly serverBuild: ServerBuild;
  }
}

app.all(
  '*',
  createRequestHandler({
    getLoadContext() {
      const context = new RouterContextProvider()
      Object.assign(context, {
        serverBuild: getBuild()
      });
      
      return context
    }
}));
celest pebble
#

Hey, thanks for that! I'm not intending to use migration api, just have one loader dependent on it so I'd rather try to do all in one go ;D I'll give a try with using a file that both can import and see what comes out of it

turbid glen
mellow shadow
#

What does getBuild return?

celest pebble
#
async function getBuild(): Promise<{error: unknown; build: ServerBuild}> {
  try {
    const build = viteDevServer
      ? await viteDevServer.ssrLoadModule('virtual:react-router/server-build')
      : // @ts-expect-error - the file might not exist yet but it will
        await import('../build/server/index.js')

    return {build: build as unknown as ServerBuild, error: null}
  } catch (error) {
    // Catch error and return null to make express happy and avoid an unrecoverable crash
    console.error('Error creating build:', error)
    return {error: error, build: null as unknown as ServerBuild}
  }
}
celest pebble