Repository URL to install this package:
|
Version:
1.2.6 ▾
|
/**
* @file React application middleware, supports server side rendering.
* @see https://reactjs.org/docs/react-dom-server.html#rendertostaticmarkup
*/
import { isString } from 'uxui-modules/exotic'
import { oneRouter } from 'uxui-modules/router'
import { fromReqResToRespondFromCacheExistence } from '../middleware/cacheMiddleware'
import { renderUsingServerSideRendering } from './renderWithServerSide'
import { renderWithoutServerSide } from './renderWithoutServerSide'
import { Request, Response } from './typings'
import { respondError } from './responders'
/**
* this is the critical first step so we can have a url on the server
*/
function setOneRouterUrl(req: Request) {
oneRouter.oneUrl = req.oneUrl
oneRouter.urlFromExpress = req.oneUrl || {
full: 'webpack_hmr',
}
}
function reactApplicationMiddleware(req: Request, res: Response) {
setOneRouterUrl(req)
/**
* @todo - probably want to add a header
*/
if (req.SHOULD_CACHE_SSR) {
const success = fromReqResToRespondFromCacheExistence(req, res)
if (success === true) {
return
}
}
/**
* Ensure a nonce has been provided to us.
* @see server/middleware/security.js for more info.
*/
const nonce = res.locals.nonce
if (!isString(nonce)) {
console.warn('@todo - no nonce')
// throw new Error('A "nonce" value has not been attached to the res')
}
/**
* It's possible to disable SSR, which can be useful in development mode.
* In this case traditional client side only rendering will occur.
*/
if (process.env.DISABLE_SSR === 'true') {
console.log('[ssr] DISABLED!!!', { requestUrl: oneRouter.urlFromExpress })
renderWithoutServerSide(res, nonce)
} else {
console.debug('[ssr] ==> Handling react route __WITH__ SSR')
console.info({ requestUrl: oneRouter.urlFromExpress })
try {
renderUsingServerSideRendering(req, res, nonce)
} catch (renderingException) {
console.error(
'[EXCEPTION_ALERT] [ssr] renderingException: ',
renderingException
)
respondError(res, renderingException)
}
}
}
export {
reactApplicationMiddleware,
reactApplicationMiddleware as reactApplication,
renderUsingServerSideRendering as render,
}
export default reactApplicationMiddleware