I'm doing SSR for my app (for robots only).
The render of the <App/> might result in a not found route.
I need to detect when that render ends in a NOT_FOUND route so I can return a res.sendStatus(404); from my express server.
I'm following this tutorial from the official docs of react-router.
I have a "catch all" route, that will render a 404 Page and will add that information to the staticContext:
AllRoutes.ts
<Route exact path={"*"} render={({ staticContext }) => {
if (staticContext) {
staticContext.statusCode = 404;
}
return <Page404/>;
}}/>
The type inferred for the staticContext object inside the render prop of the Route component is:
And it seems that its only property is an optional statusCode?: number property.
On the SERVER side, this is what I do:
ssrApp.tsx
import App from "@src/App";
import { renderToString } from "react-dom/server";
import { StaticRouter } from "react-router-dom";
// ...
const context = {}; // <<< WHAT TO TYPE THIS VARIABLE ?
const appHtml = renderToString(
<StaticRouter location={req.url} context={context}>
<App/>
</StaticRouter>
);
res.status(context.statusCode || 200).send(appHtml);
The type for the context prop of the <StaticRouter> component is StaticRouterContext:
It accepts the empty const context= {}; prop. But it complains when I try to access the statusCode property out of it.
All the types mentioned here seem to come from the package @types/react-router or @types/react-router-dom, not really sure which one.
@types/react-router/index.d.ts
export interface StaticContext {
statusCode?: number;
}
export interface RouteComponentProps<
Params extends { [K in keyof Params]?: string } = {},
C extends StaticContext = StaticContext,
S = H.LocationState
> {
history: H.History<S>;
location: H.Location<S>;
match: match<Params>;
staticContext?: C;
}
How can I type my context object? So far, I haven't been able to import the StaticRouterContext or StaticContext from anywhere.




