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
onserver.ts
On your
cookie.service.ts