Server-side rendering
document.cookie doesn’t exist on the server, so CookieService does nothing there. For apps that use Angular SSR, use ngx-cookie-service-ssr instead. It has the same API as CookieService and also works while Angular renders on the server.
-
Install
ngx-cookie-service-ssr(instead ofngx-cookie-service):Terminal window npm install ngx-cookie-service-ssrTerminal window pnpm add ngx-cookie-service-ssrTerminal window yarn add ngx-cookie-service-ssr -
Inject
SsrCookieService:import { inject } from '@angular/core';import { SsrCookieService } from 'ngx-cookie-service-ssr';const cookieService = inject(SsrCookieService);const theme = cookieService.get('theme'); // works on the server and in the browser -
Serve the app with Angular’s
AngularNodeAppEngineorAngularAppEngine(the default for apps created withng new --ssr). They provide theREQUESTandRESPONSE_INITtokens the service reads from, so there is nothing else to configure.
What happens on the server
Section titled “What happens on the server”- Reading.
get(),check()andgetAll()read the incoming request’sCookieheader. They also see cookies set or deleted earlier while rendering the same request, whatever theirpathordomain. - Writing.
set(),delete()anddeleteAll()addSet-Cookieheaders to the response. - Extra options. On the server you can also pass
httpOnly: trueandmaxAge(in seconds).
// Runs on the server: sent to the browser as a Set-Cookie header the page's scripts can't read.cookieService.set('session', sessionId, { httpOnly: true, secure: true, sameSite: 'Strict', maxAge: 3600, path: '/' });Custom server
Section titled “Custom server”If your server doesn’t render through Angular’s app engine, provide the incoming request yourself so the service can read its cookies:
import { REQUEST } from '@angular/core';
const providers = [{ provide: REQUEST, useValue: request }];The service reads cookies from a Web Request (headers.get('cookie')) or from an Express request (req.get('cookie') or req.headers.cookie). Without RESPONSE_INIT, cookies set on the server are not sent to the browser.
A small SSR app with login, guarded routes and cookies set on the server: ngx-cookie-service-ssr-demo.netlify.app.