Skip to main content

ReactSSRMiddleware

ReactSSRMiddleware(compiler, config) ⇒ Function

A custom webpack-dev-server middleware for performing server side rendering and live reload when server code has modification

Returns: Function - The middleware function

ParamTypeDescription
compilerObjectThe webpack compiler
configConfigThe middleware config

ReactSSRMiddleware~Function ⇒ Promise.<void>

ParamTypeDescription
reqObjectThe request object
resObjectThe response object

ReactSSRMiddleware~Config : Object

Properties

NameTypeDescription
patchGlobalPatchGlobalThis callback allows you to patch global object without bundling a dependency to the server chunk but you need it at runtime. For example, if cloudflare worker is the production environment, you do not need to include fetch to the server chunk because fetch is runtime api But you need it in your local development environment. Default is () => {}
reqToPropsReqToPropsThis callback allows you to convert the request object to a plain object before passing to <App {...props} />. If it does not return a plain object, it will return http 500 error. Default is () => ({})
resultToResResultToResThis callback allows you to define your own function to perform http response Default callback supports status code and body.
versionstringThe version of the JS entry to be executed. If you customize version in plugin options, you need to put same value here. Default is manifest

Config~ReqToProps ⇒ Object

Returns: Object - The plain object

ParamTypeDescription
reqObjectThe request object

Config~ResultToRes ⇒ void

ParamTypeDescription
resObjectThe response object
resultObjectThe result object from the entry

Config~PatchGlobal ⇒ void

ParamTypeDescription
globalObjectThe environment global object

Example

webpack.config.js
module.exports = (env, argv) => {
const version = `${argv.version}.${argv.mode}`
return {
"devServer": {
"setupMiddlewares": (middlewares, devServer) => ([
...middlewares,
{
"name": "ReactSSRWebpackPlugin",
"path": "*",
"middleware": ReactSSRMiddleware(
devServer.compiler,
{
"patchGlobal": (global) => {
global.fetch = require("node-fetch")
},
"reqToProps": (req) => ({
"url": url.parse(req.originalUrl, true),
"headers": req.headers,
}),
"resultToRes": (res, result) => {
const {body, statusCode} = result;
res.writeHead(
statusCode,
{
"Content-Type": "text/html"
}
)
res.end(result);
},
version,
}
),
},
]),
}
};
}