potato
potato

Reputation: 4589

Configure angular project to send http cookie in development mode

I've written a PHP backend that checks if a request is coming from an authorized user. This is done as simple as using the following code

if(!isset($_SESSION["id"])){
    http_response_code(403);
    die("Error. Unauthorized user.");  
}

This is perfectly okay in production, but in development I face issues, because angular app running on local development server does not send cookies (nor does the server store it).

How can I configure angular server/app to send session cookies during development? I am using the following code to start an app

ng serve --port 4000 --host example.com --ssl true --sslKey path --sslCert path2

UPDATE

I don't want to change my app logic or anything. this is solley to make development manageable. I need to send cookies at ng serve or configure node server to send cookie when it operates. Also if use one version in production, and another in development (as the forcefully implied answer suggests), I need to change it every time push an update and then change it back, leaving me with 2 versions. terrible, terrible practice

UPDATE 2:

For additional answer see this Q&A: sending cookies in Angular app and Access-Control-Allow-Origin in development mode

Upvotes: 0

Views: 2414

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34593

It's pretty straightforward to pass cookies on every request. ng serve doesn't provide a way to turn this feature on, but you could pass cookies conditionally depending on your environment settings:

Here's a sample interceptor:

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { environment } from '@app/environments/environment.ts'

@Injectable()
export class CustomHttpInterceptor implements HttpInterceptor {

  intercept (httpRequest: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const clonedRequest = httpRequest.clone({
      withCredentials: environment.sendCookies,
    });

    return next.handle(clonedRequest);
  }

}

In your environment.ts you can set sendCookies to true and in environment.prod.ts, set it to false. This way you still only have one version of your application, but different behavior where you need it.

Upvotes: 3

Related Questions