One issue I came across while building kothakotha was during the implementation of the like system. An anonymous like system requires tracking sessions and that meant using cookies. My issue was that while navigating on kothakotha worked as each cookie was being sent to the backend for each call made, a page refresh would not send a cookie and thus a client would not know whether they had liked a post. What we want to do is always send the cookie for every request in Angular SSR. To do this, we create a cookie forwarding interceptor.
src/app/interceptors/cookie-forwarding.interceptor.ts
import { HttpInterceptorFn } from '@angular/common/http';
import { inject, REQUEST } from '@angular/core';
export const cookieForwardingInterceptor: HttpInterceptorFn = (req, next) => {
const request = inject(REQUEST, { optional: true }) as Request | null;
let modifiedReq = req;
if (typeof window === 'undefined' && request instanceof Request) {
// Use the Web API Request.headers.get() method
const cookieHeader = request.headers.get('cookie') || request.headers.get('Cookie');
console.log('🍪 Found cookies:', cookieHeader);
if (cookieHeader) {
modifiedReq = req.clone({
setHeaders: { 'Cookie': cookieHeader },
withCredentials: true
});
console.log('✅ Added cookies to SSR request');
}
} else if (typeof window !== 'undefined') {
// Client-side
modifiedReq = req.clone({ withCredentials: true });
}
return next(modifiedReq);
};Apply the interceptor to the app.config.ts.
src/app/app.config.ts
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideClientHydration, withEventReplay } from '@angular/platform-browser';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { cookieForwardingInterceptor } from './interceptors/cookie-forwarding.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
provideBrowserGlobalErrorListeners(),
provideZonelessChangeDetection(),
provideRouter(routes), provideClientHydration(withEventReplay()),
provideHttpClient(withFetch(), withInterceptors([cookieForwardingInterceptor]))
]
};If you have cookies stored on the browser, they should now be sent every page refresh from Angular SSR! Now you know whether a post is liked or not at all times on kothakotha.
