Gaurav Aggarwal
Gaurav Aggarwal

Reputation: 10197

ngx-cookie - blank cookie object in server side rendering

I have a angular application in which angular universal is enabled and i am rendering data from API but that includes the work of cookies. I make API call after checking a value in user browser cookies.

But for Angular SSR(server side rendering) there is no cookie and i am getting {} blank object when trying to use this console.log(this.cookie.getAll());.

I am using ngx-cookie package and my installation is this

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { SlickCarouselModule } from 'ngx-slick-carousel';
import { SharedModule } from './shared/shared.module';
import { CookieModule } from 'ngx-cookie';

import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';

import { CommonModule } from '@angular/common';
import { TransferHttpCacheModule } from '@nguniversal/common';
import { NgtUniversalModule } from '@ng-toolkit/universal';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'serverApp' }),
    CookieModule.forRoot(),
    AppRoutingModule,
    HttpClientModule,
    CommonModule,
    TransferHttpCacheModule,
    NgtUniversalModule,
    SlickCarouselModule,
    SharedModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.server.module.ts

import { NgModule } from '@angular/core';
import { ServerModule, ServerTransferStateModule } from '@angular/platform-server';
import { CookieService, CookieBackendService } from 'ngx-cookie';

import { AppModule } from './app.module';
import { AppComponent } from './app.component';
import { ModuleMapLoaderModule } from '@nguniversal/module-map-ngfactory-loader';
import { SharedModule } from './shared/shared.module';

@NgModule({
  imports: [
    AppModule,
    ServerModule,
    ModuleMapLoaderModule,
    ServerTransferStateModule,
    SharedModule
  ],
  bootstrap: [AppComponent],
  providers: [{ provide: CookieService, useClass: CookieBackendService }]
})
export class AppServerModule {}

server.ts

I have applied this

app.get('*', (req, res) => {
  res.render('index', {
    req: req,
    res: res,
    providers: [
      {
        provide: 'REQUEST', useValue: (req)
      },
      {
        provide: 'RESPONSE', useValue: (res)
      }
    ]
  });
});

Still i can only access cookies in browser but not server side.

Any help would be appreciated.

Upvotes: 5

Views: 1427

Answers (1)

ferhado
ferhado

Reputation: 2604

You can send cookies with every request to server using Interceptor
Here is an example how to use it:

intercreptor.service.ts

import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest } from '@angular/common/http';

import { Observable } from 'rxjs';
import { CookieService } from 'ngx-cookie';

@Injectable()

export class InterceptorService implements HttpInterceptor {

  constructor(private cookies: CookieService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    let token = this.cookies.get("my-access-token");

   if(token) req = req.clone({
      setHeaders: { Authorization: `Bearer ${token}`}
    });

    return next.handle(req)
  }

}

intercreptor.module.ts

import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { InterceptorService } from './interceptors/authorization';

@NgModule({
  imports: [
    HttpClientModule
  ],
  providers: [{
      provide: HTTP_INTERCEPTORS,
      useClass: InterceptorService,
      multi: true
   }]
})

export class InterceptorModule { }

and import InterceptorModule into your app.module.ts

Upvotes: 1

Related Questions