skip to Main Content

new method of ssr introduced in angular 17. how can i change status code of express response in angular components now?
previously i changed the response like this:

import { RESPONSE } from '@nguniversal/express-engine/tokens';
import { Response } from 'express';  

constructor(@Optional() @Inject(RESPONSE) private response: Response)


this.response.status(this.statusCode);

with this i could change the status code. for example if i met the not-found component i had to change the status code to 404 for SEO reasons.

2

Answers


  1. The tokens aren’t exported anymore by @angular/ssr.

    What the migration schematics currently does is that is creates them :

    import { InjectionToken } from '@angular/core';
    import { Request, Response } from 'express';
    export const REQUEST = new InjectionToken<Request>('REQUEST');
    export const RESPONSE = new InjectionToken<Response>('RESPONSE');
    

    An you’ll need to provide them :
    It could look something like that :

    export function app(): express.Express {
        documentFilePath: indexHtml,
        url: `${protocol}://${headers.host}${originalUrl}`,
        publicPath: distFolder,
        providers: [
          { provide: APP_BASE_HREF, useValue: baseUrl },
          { provide: RESPONSE, useValue: res },
          { provide: REQUEST, useValue: req })
       ],
    }
    

    Here is the PR that introduced that improvement for the schematics

    Also as a note, ng serve doesn’t use server.ts (it doesn’t use express. The recommended approach to treat the tokens set in server.ts as optional.

    Login or Signup to reply.
  2. You should create src/express.token.ts with this code :

    import { InjectionToken } from '@angular/core';
    import { Request, Response } from 'express';
    export const REQUEST = new InjectionToken<Request>('REQUEST');
    export const RESPONSE = new InjectionToken<Response>('RESPONSE');
    

    In server.ts and in your component use :

    import {RESPONSE} from "./src/express.tokens";
    import {REQUEST} from "./src/express.tokens";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search