@rowanmanning/hijack-express-render
Override an Express (4.x) application's render methods. This function replaces the app.render
and response.render
methods of an Express application, allowing you to bypass Express view rendering entirely.
This allows you to implement your own template resolution and caching, but retain the standard Express API.
Table of Contents
Requirements
This library requires the following to run:
- Node.js 18+
Usage
Install with npm:
npm install @rowanmanning/hijack-express-render
Load the library into your code with a require
call:
const hijackExpressRender = require('@rowanmanning/hijack-express-render');
Create an Express application and call hijackExpressRender
with this and a new render method (see Render Methods below):
const express = require('express');
const hijackExpressRender = require('@rowanmanning/hijack-express-render');
const app = express();
hijackExpressRender(app, yourRenderMethod);
The hijackExpressRender
also returns the Express application, so you can do this in one line:
const app = hijackExpressRender(express(), yourRenderMethod);
Hijacking of the render methods must happen before any middleware that uses app.render
or response.render
. It's safest to hijack immediately after creating the Express application.
Render Methods
The render method you can pass into hijackExpressRender
must:
- Accept two parameters…
-
view
: The name of the view to render (normally a string). This will not be relative to the Express "view" directory – it is exactly what was passed intoapp.render
orresponse.render
. Your method must handle its own template resolution and caching. You may also use a non-string here if your renderer supports this -
context
: The render context (as an object). This will be defaulted usingapp.locals
andresponse.locals
in the same way as the default Express rendering engine
-
- Return a
Promise
which resolves with the rendered template. This is normally a string but can be any type that's accepted byresponse.send
Example with a Promise:
function renderMethod(view, context) {
return Promise.resolve('result');
}
Example with an async function:
async function renderMethod(view, context) {
return 'result';
}
Contributing
The contributing guide is available here. All contributors must follow this library's code of conduct.
License
Licensed under the MIT license.
Copyright © 2019, Rowan Manning