How to Use window, document, location in angular SSR applicatoin

Discussão em 'Angular' iniciado por Kishan Bhola, Dezembro 4, 2024.

  1. Kishan Bhola

    Kishan Bhola Guest

    I have just created a simple Angular SSR application using Angular CLI: 18.2.12.

    I am not using ngExpressEngine, but I am using @angular/platform-server

    The application works fine with npm run build:ssr and npm run serve:ssr.

    However, when I use built-in browser objects like localStorage, sessionStorage, window, location, document, or isBrowser, I encounter errors.

    I understand that these objects are not accessible on the server.

    In my application, these variables (e.g., localStorage and window) are used extensively. I tried using libraries like Domino and JSDOM, but they didn’t work properly.

    I also referred to this post: Angular CLI - How to use window, document, or location in environment.ts.

    Still, I couldn’t find a better solution.

    Here is my server.ts file:

    import 'zone.js/node';
    import { renderModule } from '@angular/platform-server';
    import express from 'express';
    import { join } from 'path';
    import AppServerModule from './src/main.server';
    // import { readFileSync } from 'fs';
    // import { JSDOM } from 'jsdom'


    const app = express();
    const PORT = process.env['PORT'] || 4000;
    const DIST_FOLDER = join(process.cwd(), 'dist/angular-ssr-project/browser');

    // Serve static files
    app.use(express.static(join(DIST_FOLDER, 'browser'), {
    maxAge: '1y',
    index: false
    }));


    // Serve SSR page
    app.get('*', (req, res) => {
    renderModule(AppServerModule, {
    document: '<app-root></app-root>',
    url: req.url
    }).then(html => {
    res.send(html);
    }).catch(err => {
    console.error('SSR Rendering Error:', err);
    res.status(500).send('Error during SSR rendering');
    });
    });

    // Start the server
    app.listen(PORT, () => {
    console.log(`Node Express server listening on http://localhost:${PORT}`);
    });

    // const dom = new JSDOM('<!doctype html><html><body></body></html>');
    // global['window'] = dom.window;
    // global['document'] = dom.window.document;
    // ...
    // ...

    // const template = readFileSync(join(DIST_FOLDER, 'index.html')).toString();
    // const win = createWindow(template);
    // global['window'] = win as any;
    // global['document'] = win.document;
    // global['navigator'] = win.navigator;

    // ...
    // ...

    Continue reading...

Compartilhe esta Página