Express createFetchRequest
This package is just about a simple function used to create a fetch request from an Express request.
This is needed for instance for a React project with SSR (https://reactrouter.com/en/main/routers/create-static-handler#createstatichandler).
Install
npm install express-create-fetch-request
Usage
import { createFetchRequest } from 'express-create-fetch-request';
export async function myExpressMiddleware(req, res) {
const fetchRequest = createFetchRequest(req, res);
...
}
React SSR Example
import React from 'react';
import { StaticRouterProvider } from 'react-router-dom/server';
import { createStaticHandler, createStaticRouter } from 'react-router-dom/server';
import { createFetchRequest } from 'express-create-fetch-request';
import Component, { loader, ErrorBoundary } from './my-app';
const routes = [{ path: '/', loader, Component, ErrorBoundary }];
export async function renderHtml(req, res) {
const { query, dataRoutes } = createStaticHandler(routes);
const fetchRequest = createFetchRequest(req, res);
const context = await query(fetchRequest);
if (context instanceof Response) {
throw context;
}
const router = createStaticRouter(dataRoutes, context);
return ReactDOMServer.renderToString(
<React.StrictMode>
<StaticRouterProvider router={router} context={context} />
</React.StrictMode>
);
}
Credits
Author
Adrien Febvay https://github.com/adrien-febvay