Skip to content

Platform Server - Attach cookies to HTTP requests #15730

Open

Description

@Reuvenc

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

  1. kukjevov commented on Apr 4, 2017

    @kukjevov
    Contributor

    Hi this is a problem of xhr2 module.

    I dont have solution, but i have workaround that works nice :).

    At the beginning of your main-server.ts file add these lines

    import * as xhr2 from 'xhr2';
    
    //HACK - enables setting cookie header
    xhr2.prototype._restrictedHeaders.cookie = false;

    This allows you to send cookie header. Not clean solution, but it looks like only one so far.

    Hope this helps :)

  2. sangeet003 commented on Apr 5, 2017

    @sangeet003

    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

  3. kukjevov commented on Apr 5, 2017

    @kukjevov
    Contributor

    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: string

    Also i have this code that is in method that is used for retrieving cookies this code

            if(isBlank(this._serverCookies))
            {
                result = regexp.exec(document.cookie);
            }
            else
            {
                result = regexp.exec(this._serverCookies);
            }

    in another file i have

    /**
     * Token is used to transfer server cookie header
     */
    export const SERVER_COOKIE_HEADER: InjectionToken<string> = new InjectionToken<string>('serverCookieHeader');

    SERVER_COOKIE_HEADER is provided only as provider for main-server.ts and value for this is obtained in server.js with this value req.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.

  4. added
    area: server
    on Apr 5, 2017
  5. sangeet003 commented on Apr 6, 2017

    @sangeet003

    @kukjevov where are the packages prefixed with @ng coming from?
    NPM couldn't find it.

  6. kukjevov commented on Apr 6, 2017

    @kukjevov
    Contributor

    Well packages prefixed @ng are 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.

  7. sangeet003 commented on Apr 6, 2017

    @sangeet003

    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.

  8. kukjevov commented on Apr 6, 2017

    @kukjevov
    Contributor

    I had exactly same problem, and now i know it is working, i will provide you some code tomorrow :)

  9. sangeet003 commented on Apr 6, 2017

    @sangeet003

    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):

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AppComponent } from './app.component';
    import { AppModule } from './app.module';
    import { BrowserTransferStateModule } from '../modules/transfer-state/browser-transfer-state.module';
    
    @NgModule({
    	bootstrap: [ AppComponent ],
    	imports: [
        BrowserModule.withServerTransition({
          appId: 'my-app-id'
        }),
        BrowserTransferStateModule,
        AppModule
    	],
      providers: [
        {provide: 'REQUEST', useValue: {}}
      ]
    })
    export class BrowserAppModule {}
    

    Now in any file where you wish to access the HTTP REQUEST Object, Inject 'REQUEST' into constructor:

    constructor(@Inject('REQUEST') public request: any) {
       // Below code on SSR (Node) will return cookies that come with the browser request & on browser will return {}
       let _cookies = this.request.cookies || {};
    }
    

    Hope that's helpful :-)

  10. ItsMeDelanoDev commented on Apr 11, 2017

    @ItsMeDelanoDev

    @sangeet003 But how do you manage to receive the cookies at service side?

  11. patrickmichalina commented on May 24, 2017

    @patrickmichalina

    @dneeleman wouldn't that be a concern for the server side framework you are using?

  12. informeto commented on Jun 6, 2017

    @informeto

    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.

    
    //import these
    import { Injector } from '@angular/core';
    import { REQUEST } from '@nguniversal/express-engine/tokens';
    
    //initialize your constructor:
    constructor (private injector: Injector){}
    
    //access the request with:
      req = this.injector.get(REQUEST);
      if(req.headers.cookie){
         doYourOperation(req.headers.cookie);
       }
    
    
    

    To make sure things dont break on client side, use isPlatformServer(platformId) thingy before you access the request.

  13. 916422 commented on Jun 10, 2017

    @916422

    @PUSHPANN

    ERROR { Error: Uncaught (in promise): Error: No provider for InjectionToken REQUEST!
    Error: No provider for InjectionToken REQUEST!
    How do we solve this?

  14. informeto commented on Jun 12, 2017

    @informeto

    @916422
    Are you checking if the platform is server before trying to access the request? Its only accessible on server side

  15. 916422 commented on Jun 12, 2017

    @916422

    @dneeleman AOT Compile ,Is the code that runs on the server!

  16. 22 remaining items

  17. crainsaw commented on Jan 3, 2024

    @crainsaw

    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.

  18. sfd-mhrana commented on Apr 18, 2024

    @sfd-mhrana

    i am tring more than way, but i cann't solve it. Does anyone provied me any sollution for angular 17 standalone project structure?

  19. Guerric-P commented on May 4, 2024

    @Guerric-P

    For those wondering how to make it work in Angular 17, well the migration script should add the REQUEST injection token like this:

      server.get('*', (req, res, next) => {
        const { protocol, originalUrl, baseUrl, headers } = req;
    
        commonEngine
          .render({
            bootstrap: AppServerModule,
            documentFilePath: indexHtml,
            url: `${protocol}://${headers.host}${originalUrl}`,
            publicPath: distFolder,
            providers: [
              { provide: APP_BASE_HREF, useValue: baseUrl },
              { provide: RESPONSE, useValue: res },
              { provide: REQUEST, useValue: req }
            ],
          })
          .then((html) => res.send(html))
          .catch((err) => next(err));
      });

    And like @GaetanRouzies wrote, the cookies can be retrieved and forwarded easily, just dont retrieve them from request.cookies , but from request.headers.cookie instead.

  20. sfd-mhrana commented on May 4, 2024

    @sfd-mhrana
  21. diesieben07 commented on May 7, 2024

    @diesieben07

    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 from server.ts at 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 renderPage which could provide them via the environment injector.

  22. gnibeda commented on Jul 2, 2024

    @gnibeda

    For those wondering how to make it work in Angular 17, well the migration script should add the REQUEST injection token like this:

    And like @GaetanRouzies wrote, the cookies can be retrieved and forwarded easily, just dont retrieve them from request.cookies , but from request.headers.cookie instead.

    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 xhr2 and don't use fetch on the server side, but Angular gives warnings about performance issues when not using fetch. Is there a solution for using withFetch() + cookies on Node 19+(maybe some patching like globalThis.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+.

  23. fvoska commented on Jul 11, 2024

    @fvoska

    @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 fetch API that allows you to set request headers, including the Cookie header. However, it's not done automatically, so that's why you need an interceptor that does it by injecting REQUEST and modifying outgoing requests by taking request.headers.cookie and 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 REQUEST DI 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 Request and Response objects 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.

  24. gnibeda commented on Jul 11, 2024

    @gnibeda

    @fvoska, I mean that it is not related to Angular. Simple fetch call won't send cookies in Node 19+:

    return fetch('https://test.site/rest', {
            method: 'GET',
    	credentials: "include"
            headers: {
                'Content-Type': 'application/json',
                'Cookie': cookie // Won't work in Node 19+, but works in 18
            });
  25. fvoska commented on Jul 11, 2024

    @fvoska

    @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
    import express from "express";
    
    const app = express();
    const port = 8080;
    
    app.get("/endpoint-1", async (req, res) => {
      const cookie = req.headers.cookie;
      console.log(`endpoint-1 cookie: ${cookie}`);
    
      const headers = new Headers();
      if (cookie) {
        headers.set("cookie", cookie);
      }
    
      const result = await fetch("http://localhost:8080/endpoint-2", {
        headers,
      }).then((res) => res.text());
    
      res.send(result || "no cookie found");
    });
    
    app.get("/endpoint-2", (req, res) => {
      const cookie = req.headers.cookie;
      console.log(`endpoint-2 cookie: ${cookie}`);
      res.send(req.headers.cookie);
    });
    
    app.listen(port, () => {
      console.log(`Example app listening on port ${port}`);
    });

    /endpoint-1 expects a cookie, reads the cookie and makes a fetch call to /endpoint-2, forwarding the cookie. /endpoint-2 reads the cookie that was forwarded to it and returns it. Both endpoints return the cookie header value in response body.

    image

    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.

  26. gnibeda commented on Jul 11, 2024

    @gnibeda

    @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:

    req.clone({withCredentials: true, headers: new HttpHeaders({cookie: ssrCookies})});

    It works fine, but when I use withFetch() in provideHttpClient, it stops working. Maybe I have to specify something additional during request cloning when using fetch?

  27. fvoska commented on Jul 11, 2024

    @fvoska

    @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.

  28. gnibeda commented on Jul 11, 2024

    @gnibeda

    @fvoska, yes I can read it. As I said - it works without withFetch(). Only adding withFetch() to provideHttpClient breaks 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)

  29. UserGalileo commented on Nov 17, 2024

    @UserGalileo
    Contributor

    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...

  30. SteffHain commented on Nov 25, 2024

    @SteffHain

    Hi,
    i added the following to myapp. config.

    provideHttpClient(
          withFetch(),              // Register fetch for SSR
          withInterceptorsFromDi()  // Register interceptors for the browser
    ), 
    // Register the AuthInterceptor
    { provide: HTTP_INTERCEPTORS, useClass: Interceptor, multi: true }, 
    

    In my Interceptor as example i added this:

    intercept(req: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        // Clone the request to add the withCredentials option
        const authReq = req.clone({
          withCredentials: true,  // Add withCredentials to ensure cookies are sent
        });
    
        // Pass the modified request
        return next.handle(authReq);
      }
    

    This way ensures me in Angular 19 to use cookies in http requests in dev mode on "ng serve"

    Hope this helps.

  31. lukaVarga commented on Jun 10, 2025

    @lukaVarga

    In my case, adding withCredentials: true wasn'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 REQUEST and now all cookies that have been set on client side (including secure cookies) get forwarded also during SSR.

    export function cookiesInterceptor(req: HttpRequest<unknown>, next: HttpHandlerFn): Observable<HttpEvent<unknown>> {
      const ssrRequest: Request | null = inject(REQUEST);
    
      const requestToYourApi: boolean = true; // obviously you'll need to adjust this, you don't want the interceptor to add cookies to requests outside of your api
    
      if (requestToYourApi) {
        const clonedReq: HttpRequest<unknown> = req.clone({
          withCredentials: true,
          ...(
            ssrRequest ? { headers: req.headers.append('Cookie', ssrRequest.headers.get('cookie') ?? '') } : {}
          ),
        });
    
        return next(clonedReq);
      }
    
      return next(req);
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    P3area: common/httparea: serverfreq2: mediumtype: bug/fix

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions