diff --git a/README.md b/README.md index eb91905..ae1fdfc 100644 --- a/README.md +++ b/README.md @@ -225,7 +225,7 @@ app.get('^nested/subroute/my/secret/path$', (_, res) => { ## 🤖 Transforming HTML -You can specify transformer function that takes two arguments - HTML as a string and [`Request`][express-request] object - and returns HTML as a string with any string related transformation applied. It can be used to inject your custom metadata on the server-side. +You can specify transformer function that takes two arguments - HTML as a string and [`Request`][express-request] object - and returns HTML as a string with any string related transformation applied. It can be used to inject your custom metadata on the server-side. It can also be an async function if you need to retrieve the data to inject from a database or some other remote source. This transformer function is invoked right before sending the HTML to the client in the index-serving middleware that `vite-express` injects at the end of the middleware stack. @@ -312,7 +312,7 @@ ViteExpress.config({ /*...*/ }); | name | description | default | valid values | | ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------- | ----------------------------------------------------------------- | | mode | When set to development Vite Dev Server will be utilized, in production app will serve static files built with `vite build` command | `"development"` | `"development"` \| `"production"` | -| transformer | A function used to transform HTML served to the client, useful when you want to inject some metadata on the server. First argument is the HTML that is about to be sent to the client, second is the [`Request`][express-request] object. Needs to return transformed HTML as a string. | `undefined` | `undefined` \| `(html: string, req: Request) => string` | +| transformer | A function used to transform HTML served to the client, useful when you want to inject some metadata on the server. First argument is the HTML that is about to be sent to the client, second is the [`Request`][express-request] object. Needs to return transformed HTML as a string, or a Promise that resolves to the transformed HTML string. | `undefined` | `undefined` \| `(html: string, req: Request) => string \| Promise` | | ignorePaths | A regex or function used to determine if matched path/request should be ignored by Vite index.html serving logic. When defined as a function, the request will be ignored when function returns true. Example of usage: Can be used to disable Vite on `/api` paths. | `undefined` | `undefined` \| `RegExp` \| `(path: string, req: Request) => bool` | | inlineViteConfig | When set to non-undefined value, `vite-express` will be run in [`viteless mode`](#-viteless-mode) | `undefined` | `undefined` \| `ViteConfig` | diff --git a/src/main.ts b/src/main.ts index ecec391..abcc28e 100644 --- a/src/main.ts +++ b/src/main.ts @@ -32,7 +32,7 @@ const Config = { | ((path: string, req: express.Request) => boolean), transformer: undefined as | undefined - | ((html: string, req: express.Request) => string), + | ((html: string, req: express.Request) => string | Promise), }; type ConfigurationOptions = Partial; @@ -50,7 +50,7 @@ function isStaticFilePath(path: string) { return path.match(/(\.\w+$)|@vite|@id|@react-refresh/); } -function getTransformedHTML(html: string, req: express.Request) { +async function getTransformedHTML(html: string, req: express.Request) { return Config.transformer ? Config.transformer(html, req) : html; } @@ -224,8 +224,16 @@ async function injectViteIndexMiddleware( if (indexPath === undefined) return next(); const template = fs.readFileSync(indexPath, "utf8"); - const html = await server.transformIndexHtml(req.originalUrl, template); - res.send(getTransformedHTML(html, req)); + let html = await server.transformIndexHtml(req.originalUrl, template); + + try { + html = await getTransformedHTML(html, req); + res.send(html); + } catch (e) { + console.error(e); + res.status(500); + return next(); + } } }); } @@ -234,14 +242,22 @@ async function injectIndexMiddleware(app: core.Express) { const distPath = await getDistPath(); const config = await getViteConfig(); - app.use(config.base, (req, res, next) => { + app.use(config.base, async (req, res, next) => { if (isIgnoredPath(req.path, req)) return next(); const indexPath = findClosestIndexToRoot(req.path, distPath); if (indexPath === undefined) return next(); - const html = fs.readFileSync(indexPath, "utf8"); - res.send(getTransformedHTML(html, req)); + let html = fs.readFileSync(indexPath, "utf8"); + + try { + html = await getTransformedHTML(html, req); + res.send(html); + } catch (e) { + console.error(e); + res.status(500); + return next(); + } }); } @@ -263,7 +279,7 @@ async function startServer(server: http.Server | https.Server) { ); server.on("close", async () => { - await vite.close() + await vite.close(); server.emit("vite:close"); });