change status code of Response in @angular/ssr in angular 17

1.3k views Asked by At

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.

4

There are 4 answers

2
Matthieu Riegler On

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.

0
Fabian Lainé On

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";
3
Saeed On

The dev environment is the problem which ng server totally ignores server.ts
Related issue on github:
https://github.com/angular/angular-cli/issues/26323
Now it has freq3: high label (many people faced the same issue)

0
chirag kalsariya On

this is important for resolve this problem

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.

to test

You need to build your app and than serve it, If try to do this thing using ng serve, It will not work