How to setup apollo-angular in angular v16 or v17 to make it SSR (Server side rendered)

300 Views Asked by At

In angular v16 or v17 the application configuration has the option/provider 'provideHttpClient(withFetch())'.

import { ApplicationConfig } from '@angular/core';
import { provideRouter, withInMemoryScrolling } from '@angular/router';

import { routes } from './app.routes';
import { provideClientHydration } from '@angular/platform-browser';
import { provideHttpClient, withFetch, withInterceptorsFromDi, ɵwithHttpTransferCache } from '@angular/common/http';
import { graphqlProvider } from './graphql.provider';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes, withInMemoryScrolling({
    anchorScrolling: 'enabled'
  })), provideClientHydration(), provideHttpClient(
    withFetch(),
  ), graphqlProvider]
};

This works great with GET requests and every get request is unique. As the documentation says the HttpClient when used with fetch API. But When it comes to graphql (I am using apollo-angular library), for every query and mutation the endpoint is same ( '/graphql' ) and request method is POST. So I finding hard time to understand and resolve this problem.

I tried adding this ssrMode: true in graphql provider code

import { Apollo, APOLLO_OPTIONS } from 'apollo-angular';
import { HttpLink } from 'apollo-angular/http';
import { ApplicationConfig, inject } from '@angular/core';
import { ApolloClientOptions, InMemoryCache } from '@apollo/client/core';

const uri = 'http://localhost:1337/graphql'; // <-- add the URL of the GraphQL server here
export function apolloOptionsFactory(): ApolloClientOptions<any> {
  const httpLink = inject(HttpLink);
  return {
    link: httpLink.create({ uri }),
    cache: new InMemoryCache(),
    ssrMode: true
  };
}

export const graphqlProvider: ApplicationConfig['providers'] = [
  Apollo,
  {
    provide: APOLLO_OPTIONS,
    useFactory: apolloOptionsFactory,
  },
];

but that seems not enough and involves different methods I guess.

1

There are 1 best solutions below

1
Matthieu Riegler On

provideClientHydration() accepts withHttpTransferCacheOptions() as argument where you can pass includePostRequests: true

So you need :

provideClientHydration(withHttpTransferCacheOptions(includePostRequests: true))