Demystifying Angular Output Hashing: Ensuring Users See Your Latest Releases
Have you ever encountered the issue of browser caching when deploying new features in your Angular application? You release new functionality, but when you navigate through your app, the changes don't seem to take effect until you manually refresh the page. This frustrating behavior is a result of browser caching, where browsers store CSS, HTML, media files, and other assets to improve rendering performance. While Angular offers the --output-hashing flag to manage caching by defining cache-busting output filenames, sometimes it may not work as expected.
In this article, we'll explore a solution to this problem and learn how to ensure that users see the latest updates immediately after a release. We'll leverage a combination of Angular, Express.js, and browser storage to achieve this.
Environment:
- Angular application.
- Server application (Express.js).
Server-Side Configuration:
Our journey begins on the server side. To make this solution work, we’ll first add a variable to our server’s “.env” file, which we’ll name “releaseVersion.”
// .env
releaseVersion=1Next, in our server project, we’ll use “express-session” to manage user sessions. After a user logs in, we’ll add the current release version to the user’s session object:
// login route
req.session.releaseVersion = process.env.releaseVersionNow, let’s create a middleware called CheckReleaseVersion to inspect and possibly update the releaseVersion property in the req.session object in the user's session.
// check-release-version.middleware.ts
import {ExpressMiddlewareInterface, Middleware, Req, Res} from "routing-controllers";
import {Request, Response} from "express";
@Middleware({ type: "before" })
export class CheckReleaseVersion implements ExpressMiddlewareInterface {
use(@Req() req: Request, @Res() res: Response, next?: (err?: any) => any): any {
const authData = req.session;
// if release version is not set
if (authData && !authData.releaseVersion) {
authData.releaseVersion = process.env.releaseVersion;
res.status(202).send({ releaseVersion: process.env.releaseVersion});
// if release version is not equal to current release version
} else if (authData && authData.releaseVersion !== process.env.releaseVersion) {
authData.releaseVersion = process.env.releaseVersion;
res.status(202).send({ releaseVersion: process.env.releaseVersion});
}
else {
// if release version is equal to current release version
next();
}
}
}This middleware will handle three different conditions:
- If
req.sessionexists butreleaseVersionis not set:
- It sets
req.session.releaseVersionto the value ofprocess.env.releaseVersion. - It sends a
202status response with a JSON object containing the currentreleaseVersion.
2. If req.session exists and releaseVersion is not equal to the value of process.env.releaseVersion:
- It updates
req.session.releaseVersionto the currentprocess.env.releaseVersion. - It sends a
202status response with a JSON object containing the updatedreleaseVersion.
3. If req.session exists and releaseVersion is already equal to the value of process.env.releaseVersion:
- It calls the
next()function to pass control to the next middleware in the chain.
In this case, the middleware checks all requests you send and when a user makes the first request to the server after release we send a 202 status code. Also, you can choose any other status code. We will need to match it to the Angular application.
Front-End Implementation:
Now, let’s move to the front end, where we’ll create an HTTP interceptor called HttpRequestInterceptor to modify outgoing HTTP requests and handle HTTP responses.
// http-request.inreceptor.ts
import { Injectable } from '@angular/core';
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest, HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import {tap} from "rxjs/operators";
@Injectable()
export class HttpRequestInterceptor implements HttpInterceptor {
constructor() {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
req = req.clone({
withCredentials: true
});
return next.handle(req).pipe(
tap((event) => {
if (event instanceof HttpResponse) {
// Check the HTTP status code
if (event.status === 202) {
if (event.body && event.body.releaseVersion) {
localStorage.setItem('releaseVersion', event.body.releaseVersion);
}
// Reload the page
location.reload();
}
}
})
);
}
}This interceptor performs the following tasks:
- If the HTTP status code of the response is
202, it enters a conditional block. - It checks if the response body contains a
releaseVersionproperty and, if so, stores it in the browser'slocalStorage. - Finally, it reloads the current page using
location.reload(). This is crucial for updating the user interface when the server responds with a202status code, indicating that a refresh is necessary.
Additional Functionality for Cases When the User is Not Logged In:
If you’re familiar with how session objects work, you may know that they are typically destroyed after a user logs out. In such cases, we need to implement additional functionality to handle situations when the user is not logged in.
For instance, if you redirect a user to a dashboard page after login, you can create a resolver for the dashboard route. This resolver will ensure that the release version is checked and managed even when the user is not logged in.
// check-release.service.ts
import {inject, Injectable} from '@angular/core';
import {AuthenticationService} from "./auth.service";
@Injectable({
providedIn: 'root'
})
export class ReleaseService {
/**
* Check release version
* description: Check release version and save it to localStorage. Resolver for dashboard route in dashboard-routing.module.ts
* @return {boolean}
*/
checkReleaseVersion(): boolean {
const authDataReleaseVersion = inject(AuthenticationService).authData.releaseVersion;
const currentReleaseVersion = localStorage.getItem('releaseVersion');
if (!currentReleaseVersion || authDataReleaseVersion !== currentReleaseVersion) {
localStorage.setItem('releaseVersion', authDataReleaseVersion);
return true;
}
return false;
}
}This service appears to be responsible for checking and managing the release version of an application. Here’s a description of what this service does:
1. Retrieve the release version from the authData property of the AuthenticationService. This implies that the AuthenticationService contains user authentication data, including the release version.
2. Retrieve the current release version stored in the browser’s localStorage.
3. Check if the currentReleaseVersion is either not set (null or undefined) or not equal to the authDataReleaseVersion.
4. Update localStorage and return a boolean.
After defining the checkReleaseVersion method in the ReleaseService, you can set it as a resolver in your route configuration, ensuring that the release version is checked before loading the dashboard module:
const routes: Routes = [
{
path: 'dashboard',
loadChildren: () => import('./dash.module').then(module => module.DashModule),
resolve: {isNewRelease: () => inject(ReleaseService).checkReleaseVersion()}
}
];To complete the implementation, you’ll need to add a route subscription within your dashboard component. This subscription will listen for changes in the isNewRelease parameter resolved by the route resolver. If a new release is detected, it triggers a page reload to ensure the user sees the latest updates:
// dashboard.component.ts
const checkRelease: Subscription = this.activatedRoute.data.subscribe(
({isNewRelease}) => {
if (isNewRelease){
location.reload();
}
});
this.subscription.add(checkRelease);With this additional functionality, you ensure that even in scenarios where a user isn’t logged in, the release version is managed, and the user interface is refreshed when a new release is detected, providing a seamless experience for all users.
In summary, we’ve addressed the challenge of ensuring users see the latest updates immediately after a release in an Angular application. By combining server-side session management with an HTTP interceptor on the client side, we’ve created a mechanism that detects release changes and triggers a page reload, bypassing browser caching. This approach provides a seamless user experience and helps prevent caching-related issues when rolling out new features.
Thanks for your attention, if you like this article you can 👏 , follow me, or write a comment. You can also see my previous articles: