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
Param | Type | Description |
---|---|---|
compiler | Object | The webpack compiler |
config | Config | The middleware config |
ReactSSRMiddleware~Function ⇒ Promise.<void>
Param | Type | Description |
---|---|---|
req | Object | The request object |
res | Object | The response object |
ReactSSRMiddleware~Config : Object
Properties
Name | Type | Description |
---|---|---|
patchGlobal | PatchGlobal | This 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 () => {} |
reqToProps | ReqToProps | This 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 () => ({}) |
resultToRes | ResultToRes | This callback allows you to define your own function to perform http response Default callback supports status code and body. |
version | string | The 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
Param | Type | Description |
---|---|---|
req | Object | The request object |
Config~ResultToRes ⇒ void
Param | Type | Description |
---|---|---|
res | Object | The response object |
result | Object | The result object from the entry |
Config~PatchGlobal ⇒ void
Param | Type | Description |
---|---|---|
global | Object | The 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,
}
),
},
]),
}
};
}