I am working on an Angular v19 project with SSR enabled for better SEO. I have two components:
If the entity does not exist, I want to redirect the user to the 404 page and return a 404 HTTP status instead of 200.
Currently, when I make a curl
request to the URL of a non-existing entity, I receive the correct 404 page content, but the HTTP status remains 200 instead of 404.
Is there a way to modify the HTTP status code to 404 from inside my 404-page-not-found component when running Angular with SSR? If not, what would be the correct approach to achieve this behavior?
Any help would be appreciated!
After several attempts, I have concluded the following points:
Using "path: '404-page-not-found', renderMode: RenderMode.Server, status: 404"
in the app.routes.server.ts
file is part of the solution.
I trigger a redirection to the 404-page-not-found
page from the server.ts
file rather than from the component.ts
file, else if handled at the component.ts
level, the page content changes, but the response status does not.
server.ts
update :
const entityRegex = /\/entity\//;
const knownEntities = ['123456789-entity', '987654321-entity'];
app.use('/**', (req, res, next) => {
if (entityRegex.test(req.baseUrl)) {
let entity = req.baseUrl.substring(8);
console.log('entity:', entity);
if (knownEntities.includes(entity)) {
next();
} else {
res.redirect('/404-page-not-found');
}
} else {
next();
}
});
This checks whether the entity exists:
next()
.status: 404
in app.routes.server.ts
ensures that a 404 status code is returned.)Pros & Cons
ā
Advantage: A proper 404
status is returned.
ā Drawback: The server.ts
file requires a knownEntitiesList
, or an API call to verify existence, which can introduce additional latency. If the entity exists, this approach results in two API calls instead of one (one server-side check and another browser-side request).
An example is available in StackBlitz
Know with this method using curl
you get:
404
status for /entity/000000000-entity
.200
status for /entity/123456789-entity
.