Repository navigation
Description
I'm submitting a ... (check one with "x")
[x] bug report => search github for a similar issue or PR before submitting
[ ] feature request
[ ] support request => Please do not submit support request here, instead see https://github.com/angular/angular/blob/master/CONTRIBUTING.md#question
Current behavior
Currently I see no option to attach cookies to a http request when the application runs on server platform.
Using Universal + angular v2.x.x allowed setting 'Cookie' header property manually, in the current version I'm getting the following warning:
Refused to set unsafe header "Cookie" (node-xhr2 library logs this warning, as it disallows setting cookie header).
Expected behavior
It should be possible to pass cookies to a http request.
It was already asked in the roadmap but no answer or suggestion was provided.
Minimal reproduction of the problem with instructions
What is the motivation / use case for changing the behavior?
Without attaching cookies to a http request, the response on the server is different than the response on the client. It also makes the usage of transfer state dangerous, since the browser will not fire the http request and will use the response received from the server.
Please tell us about your environment:
- Angular version: 4.0.0
- Browser: [all | Chrome XX | Firefox XX | IE XX | Safari XX | Mobile Chrome XX | Android X.X Web Browser | iOS XX Safari | iOS XX UIWebView | iOS XX WKWebView ]
- Language:: TypeScript 2.2.2
Activity
kukjevov commentedon Apr 4, 2017
Hi this is a problem of
xhr2module.I dont have solution, but i have workaround that works nice :).
At the beginning of your main-server.ts file add these lines
This allows you to send cookie header. Not clean solution, but it looks like only one so far.
Hope this helps :)
sangeet003 commentedon Apr 5, 2017
Even retrieving cookie does not work on Server Side.
I was able to set cookies, but couldn't retrieve the same.
Zone.current.get('cookie')The above used to work in angular2 universal starters but not in angular4
kukjevov commentedon Apr 5, 2017
Here you can see how to use cookies.
https://github.com/kukjevov/ng-universal-demo/tree/mine
I have
CookiesService, that has constructor with parameter looking like this@Optional() @Inject(SERVER_COOKIE_HEADER) private _serverCookies: stringAlso i have this code that is in method that is used for retrieving cookies this code
in another file i have
SERVER_COOKIE_HEADERis provided only as provider for main-server.ts and value for this is obtained inserver.jswith this valuereq.headers['cookie']where request is NodeJs request object.I dont want to set cookies on SSR, so i use it only for reading. It does not matter whether you have Connect, Express NodeJs server, or AspNet.Core, it works both way, because you just set cookies as string for your service for reading it. Check repository posted above, if you have any questions i can help hopefully.
sangeet003 commentedon Apr 6, 2017
@kukjevov where are the packages prefixed with
@ngcoming from?NPM couldn't find it.
kukjevov commentedon Apr 6, 2017
Well packages prefixed
@ngare mine packages all created by me and are not open source since we are using them in our company, i can provide you snippets if you want but not whole code :(.They are in private npm repository, i can run it, but you wont be able to run that project but it is working :) nicely.
sangeet003 commentedon Apr 6, 2017
The only thing I need here is to be able to authenticate user on server.
For that I need to access the cookie on server inside angular, if you can guide me with that would be great.
kukjevov commentedon Apr 6, 2017
I had exactly same problem, and now i know it is working, i will provide you some code tomorrow :)
sangeet003 commentedon Apr 6, 2017
Figured it out...
Using the below starter for angular4:
https://github.com/FrozenPandaz/ng-universal-demo
Change your ng-universal-demo/src/app/browser-app.module.ts file to look like below (Note the Providers Array):
Now in any file where you wish to access the HTTP REQUEST Object, Inject 'REQUEST' into constructor:
Hope that's helpful :-)
ItsMeDelanoDev commentedon Apr 11, 2017
@sangeet003 But how do you manage to receive the cookies at service side?
patrickmichalina commentedon May 24, 2017
@dneeleman wouldn't that be a concern for the server side framework you are using?
informeto commentedon Jun 6, 2017
My workaround for ng4
This will work with both components and services, I wasnt able to use @sangeet003 's solution in a service, but that works in a component.
To make sure things dont break on client side, use isPlatformServer(platformId) thingy before you access the request.
916422 commentedon Jun 10, 2017
@PUSHPANN
ERROR { Error: Uncaught (in promise): Error: No provider for InjectionToken REQUEST!
Error: No provider for InjectionToken REQUEST!
How do we solve this?
informeto commentedon Jun 12, 2017
@916422
Are you checking if the platform is server before trying to access the request? Its only accessible on server side
916422 commentedon Jun 12, 2017
@dneeleman AOT Compile ,Is the code that runs on the server!
22 remaining items
crainsaw commentedon Jan 3, 2024
Thank you @GaetanRouzies for the workaround. Do you know how this could be achieved for Angular 17 as well? There is no 'REQUEST' InjectionToken available anymore.
My only solution right now is to disable SSR for all non static routes using this:
nestjs/ng-universal#160 (comment)
Obviously that makes SSR almost useless :/ I hope that there will be a solution.
sfd-mhrana commentedon Apr 18, 2024
i am tring more than way, but i cann't solve it. Does anyone provied me any sollution for angular 17 standalone project structure?
Guerric-P commentedon May 4, 2024
For those wondering how to make it work in Angular 17, well the migration script should add the
REQUESTinjection token like this:And like @GaetanRouzies wrote, the cookies can be retrieved and forwarded easily, just dont retrieve them from
request.cookies, but fromrequest.headers.cookieinstead.sfd-mhrana commentedon May 4, 2024
diesieben07 commentedon May 7, 2024
While the solution posted above does work for the built application, it does not work in dev mode (
ng serve) with the new builder (@angular-devkit/build-angular:dev-server), because in this mode SSR does not use the express server fromserver.tsat all, instead an internal dev server is used with no way to access the request and/or the cookies (as far as I can tell).It would be nice if there was a way to access cookies supported by Angular itself, so that the dev server can be aware of it, too.
Edit: Finally found where the server is actually created: https://github.com/angular/angular-cli/blob/9e13a8b0c85c7f8353a061e11031bdfe4473870e/packages/angular/build/src/tools/vite/angular-memory-plugin.ts#L195-L240
It definitely looks possible to pass the request and/or the cookies to
renderPagewhich could provide them via the environment injector.gnibeda commentedon Jul 2, 2024
I didn't get it.
With Node v.19+, fetch can't send cookies anymore. I'm using
withFetch()on a SERVER SIDE(SSR), so all requests on the server side can't send cookies in the request header.Yes, I can read it using DI, yes, I can pass it to SSR fetch call, but it will be ignored by the fetch(Node 19+).
How should API calls from the server side work in Angular 17+ using
withFetch()and cookies?p.s. I know that I can patch
xhr2and don't use fetch on the server side, but Angular gives warnings about performance issues when not using fetch. Is there a solution for usingwithFetch()+ cookies on Node 19+(maybe some patching likeglobalThis.fetch = ...?p.p.s. I don't need to make it work in dev mode; I want to make it work at least in prod env. on Node 19+.
fvoska commentedon Jul 11, 2024
@gnibeda I don't see what has changed in node 19+ that would prevent attaching of cookies to requests made from SSR side to some API?
Node 18 added native
fetchAPI that allows you to set request headers, including theCookieheader. However, it's not done automatically, so that's why you need an interceptor that does it by injectingREQUESTand modifying outgoing requests by takingrequest.headers.cookieand forwarding it, as showcased by @GaetanRouzies and @Guerric-P in their comments.It seems to me that the only outstanding issue is that this does not work in dev mode because of what @diesieben07 said about dev-server not using express server, which in turn does not provide express request object under
REQUESTDI token.In my opinion, an ideal solution would be for Angular to provide some framework-agnostic value for the SSR request object that would work in all cases. By framework-agnostic, I mean that it does not depend on express nor whatever is used in dev mode. Some generic
RequestandResponseobjects that you can inject and that can be mapped to whatever is being used to handle SSR requests, be it express or anything else.p.s. it's a bit disconcerting that the stack for handling SSR requests is completely different between dev and production modes, as there might be some issues that happen in one, but not the other. Worst case scenario - something works locally, but not in production due to differences between express and vite handling of SSR requests.
gnibeda commentedon Jul 11, 2024
@fvoska, I mean that it is not related to Angular. Simple fetch call won't send cookies in Node 19+:
fvoska commentedon Jul 11, 2024
@gnibeda there is no issue with reading and sending cookies in node's native fetch methoid. In node, there is no concept of cookies per-se, like there is in browsers. From node perspective, it's just a regular HTTP header that can be received or sent.
I have created a quick example that showcases that you are able to read received cookies in node and send the cookie header in requests using
fetch.Code snippet
/endpoint-1expects a cookie, reads the cookie and makes a fetch call to/endpoint-2, forwarding the cookie./endpoint-2reads the cookie that was forwarded to it and returns it. Both endpoints return the cookie header value in response body.I have checked this on node 20, not sure about 19.
If you are having issues with this, I think there is something else wrong, as it's not a node native fetch issue.
This is getting a bit off-topic, but I wanted to make sure we can rule out that it's not a node's native fetch issue.
gnibeda commentedon Jul 11, 2024
@fvoska, thank you. Seems that issue doesn't related to Node, because your code works fine on Node v20.14.
Any ideas why, using
withFetch()on server side, prevents cookies from sending?I have following code in interceptor:
It works fine, but when I use
withFetch()inprovideHttpClient, it stops working. Maybe I have to specify something additional during request cloning when using fetch?fvoska commentedon Jul 11, 2024
@gnibeda can you verify if you can read the cookie succesfully on SSR side? i.e.
console.log(ssrCookies)in the interceptor and see what you see in terminal where the SSR process is running.gnibeda commentedon Jul 11, 2024
@fvoska, yes I can read it. As I said - it works without
withFetch(). Only addingwithFetch()toprovideHttpClientbreaks it.I've tested it with logging, cookies was provided to headers in interceptor but there is no cookies in raw headers on express side when processing API calls. (only when using
withFetch(), if I remove it, it works fine)UserGalileo commentedon Nov 17, 2024
Any update with Angular 19? 🤞 This unfortunately makes cookie-based authentication way more complicated than it needs to be. It's a frustrating experience for students to go through these hacks...
SteffHain commentedon Nov 25, 2024
Hi,
i added the following to myapp. config.
In my Interceptor as example i added this:
This way ensures me in Angular 19 to use cookies in http requests in dev mode on "ng serve"
Hope this helps.
lukaVarga commentedon Jun 10, 2025
In my case, adding
withCredentials: truewasn't enough for the cookies to be included in requests done by the server during SSR. It was enough for cookies to be included on requests done from client side, but not from server side.So I extended the interceptor to manually attach cookies to request header, based on cookies in injected
REQUESTand now all cookies that have been set on client side (including secure cookies) get forwarded also during SSR.