How to serve a static maintenance.html page with angular 19

Discussão em 'Angular' iniciado por mbagiella, Fevereiro 24, 2025.

  1. mbagiella

    mbagiella Guest

    With Angular 19 and SSR enabled, how to serve a maintenance page via server.ts ?

    I have this code from standard Angular 19 with SSR

    import { CommonEngine, isMainModule } from '@angular/ssr/node';
    import express from 'express';
    import { dirname, join, resolve } from 'node:path';
    import { fileURLToPath } from 'node:url';
    import bootstrap from './main.server';

    const serverDistFolder = dirname(fileURLToPath(import.meta.url));
    const browserDistFolder = resolve(serverDistFolder, '../browser');
    const indexHtml = join(serverDistFolder, 'index.server.html');

    const app = express();
    const commonEngine = new CommonEngine();


    app.get(
    '**',
    express.static(browserDistFolder, {
    maxAge: '1y',
    index: 'index.html',
    }),
    );

    /**
    * Handle all other requests by rendering the Angular application.
    */
    app.get('**', (req, res, next) => {
    const { protocol, originalUrl, headers } = req;

    // Rendre le document Angular
    commonEngine
    .render({
    bootstrap,
    documentFilePath: indexHtml,
    url: `${protocol}://${headers.host}${originalUrl}`,
    publicPath: browserDistFolder
    })
    .then((html) => {

    res.send(html);
    })
    .catch((err) => next(err));
    });

    /**
    * Start the server if this module is the main entry point.
    * The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
    */
    if (isMainModule(import.meta.url)) {
    const port = process.env['PORT'] || 4000;
    app.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
    });
    }

    export default app;


    I tried this but it doesn't work

    app.use((req, res, next) => {
    if (process.env['MAINTENANCE'] === 'true') {
    return res.status(503).sendFile(resolve(browserDistFolder, '../public/maintenance.html'));
    }
    next();
    });


    but It doesn't work, the file doesn't exists but the html is present in public folder

    Continue reading...

Compartilhe esta Página