I'm trying to get cookies on Angular 17 with SSR, in the past there was the REQUEST
pulled from @nguniversal/express-engine/tokens
, but since @angular/ssr I don't find where to pull REQUEST from
import { REQUEST } from '@angular/ssr'; // Module '"@angular/ssr"' has no exported member 'REQUEST'.
Or maybe there is a new way to fetch cookies.
The main thing I need is the Bearer token to add it to the header request, if there is a better way to do this, then I would be interested! (the API is on another URL, so using cookies directly wouldn't work well due to CORS).
EDIT:
After some research, I found
const REQUEST = new InjectionToken<Request>('REQUEST');
and I've added { provide: 'REQUEST', useValue: req }
to the server.ts, which looks like
server.get('*', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;
commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [
{ provide: APP_BASE_HREF, useValue: baseUrl },
{ provide: 'REQUEST', useValue: req },
],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
and finally constructor(@Optional() @Inject(REQUEST) private request: Request)
, but this returns null.
I was on the right track, but I wasn't doing it the proper way. If someone is interested here is what works.
Add APP_SSR_COOKIES
on server.ts
server.get('*', (req, res, next) => {
const { protocol, originalUrl, baseUrl, headers } = req;
commonEngine
.render({
bootstrap,
documentFilePath: indexHtml,
url: `${protocol}://${headers.host}${originalUrl}`,
publicPath: browserDistFolder,
providers: [
{ provide: APP_BASE_HREF, useValue: baseUrl },
{ provide: APP_SSR_COOKIES, useValue: req.headers.cookie },
],
})
.then((html) => res.send(html))
.catch((err) => next(err));
});
On your cookie.service.ts
// this const is loaded on the server.ts
export const APP_SSR_COOKIES = new InjectionToken<any>('APP_SSR_COOKIES');
export class CookieService {
constructor(
@Optional() @Inject(DOCUMENT) private doc: Document,
@Inject(PLATFORM_ID) private platformId: string,
@Optional() @Inject(APP_SSR_COOKIES) private ssrCookies: string
) {
this.isBrowser = isPlatformBrowser(this.platformId);
}
check(name: string): boolean {
const regExp = this.getRegExp(name);
return regExp.test(this.isBrowser ? this.doc.cookie : this.ssrCookies);
}
}