nuxt-modules / apollo

Nuxt.js module to use Vue-Apollo. The Apollo integration for GraphQL.
https://apollo.nuxtjs.org
MIT License
944 stars 198 forks source link

Cookies not sent in SSR mode #312

Open drewbaker opened 4 years ago

drewbaker commented 4 years ago

Version

v4.0.0-rc.19

Reproduction link

https://pyj86.sse.codesandbox.io

Steps to reproduce

If httpLinkOptions.credentials = true it seems the Cookie header is set when client side, but not when the SSR request is happening.

Setup nuxt.config.js like so:

    apollo: {
        authenticationType: "Basic",
        clientConfigs: {
            default: "~/plugins/apollo-config-default.js"
        }
    }

And then in apollo-config-default.js

export default function() {
    return {
        httpEndpoint: process.env.DEFAULT_ENDPOINT,
        getAuth: () => process.env.BASIC_API_TOKEN || "",
        httpLinkOptions: {
            credentials: "include"
        }
    }
}

Hard load to a public URL, like: https://pyj86.sse.codesandbox.io/

It works fine, browse to a private URL via a nuxt-link and it works fine.

Hard load into a private URL and it will give SSR node not matching server-rendered errors.

This page will only work if you are logged into backend. DM me for the logins which is here: https://stackhaus-backend.funkhaus.us /wp-admin

Public page: https://pyj86.sse.codesandbox.io/ Private page: https://pyj86.sse.codesandbox.io/featured/private-page

What is expected ?

Cookie header should be sent when both client side and SSR

What is actually happening?

SSR gives node not matching server-rendered errors

Additional comments?

I'm running WordPress as a headless CMS and trying to get preview/draft/private pages/posts working. The setup results in the backend having a different domain to your frontend, like example.com and api.example.com.

This bug report is available on Nuxt community (#c296)
drewbaker commented 4 years ago

Got more data on this error, from a custom error handler in the smart query:

 ERROR  We've got an error! GraphQL error: Internal server error                                               18:26:41

  at new ApolloError (node_modules/apollo-client/lib/bundle.cjs.js:89:24)
  at node_modules/apollo-client/lib/bundle.cjs.js:1585:32

  at node_modules/apollo-client/lib/bundle.cjs.js:2005:13
  at Set.forEach (<anonymous>)
  at node_modules/apollo-client/lib/bundle.cjs.js:2003:24
  at Map.forEach (<anonymous>)
  at QueryManager.broadcastQueries (node_modules/apollo-client/lib/bundle.cjs.js:2001:18)
  at node_modules/apollo-client/lib/bundle.cjs.js:2128:17
  at Object.next (node_modules/zen-observable/lib/Observable.js:322:23)
  at notifySubscription (node_modules/zen-observable/lib/Observable.js:135:18)
  at onNotify (node_modules/zen-observable/lib/Observable.js:179:3)
  at SubscriptionObserver.next (node_modules/zen-observable/lib/Observable.js:235:7)
  at node_modules/apollo-client/lib/bundle.cjs.js:1099:34
  at Set.forEach (<anonymous>)
  at Object.next (node_modules/apollo-client/lib/bundle.cjs.js:1098:19)
  at notifySubscription (node_modules/zen-observable/lib/Observable.js:135:18)
drewbaker commented 4 years ago

Looked into this some more today. Almost certain that cookies are not being sent for the SSR request, only on the client side requests now.

rivor commented 3 years ago

is there a fix to this? i've ran into same problem.

hauptbenutzer commented 3 years ago

@rivor We're currently running with the solution in https://github.com/nuxt-community/apollo-module/pull/358 I opened the PR for reference just now. For this to work, you'll need to add https://www.npmjs.com/package/cookie-universal-nuxt separately, as described in their docs.

rivor commented 3 years ago

@hauptbenutzer hey, thanks for the quick reply!

i had troubles with this from yesterday and i know that this used to work before when i tested. But after i deployed an app, It strangely enough stopped working and then i downgraded to ^4.0.0-rc.3 version (i read somewhere that it might help) but still didn't fix the issue.

And now when i tried to apply your PR, i had issues with the permissions and i ended up reinstalled node_modules and put back newest version and it started working without your PR, but i still do have cookies-universal-nuxt installed. Could that be the fix?

kukosek commented 3 years ago

The issue is still here in 2021. Have you guys figured out a workaround i could use? I just want the cookie client sent to nuxt server being passed to the apollo prefetch requests

dlhck commented 1 year ago

Is there any update on that?

truesteps commented 1 year ago

bump

Any updates? Even if I attach them manually, they are just not being sent for whatever reason....

        const ssrMiddleware = setContext((_, { headers }) => ({
        headers: {
            ...headers,
            Accept: 'application/json',
            'Content-type': 'application/json',
            'X-Brand': 'some-brand',
            'X-XSRF-TOKEN': decodeURIComponent($cookies.get('XSRF-TOKEN')),
        },
    }));

    const httpLink = new HttpLink({
        uri: `${$config.apiUrl}/graphql`,
        credentials: 'include'
    });

    const link = from([ssrMiddleware, httpLink]);
jf908 commented 6 months ago

This issue is very old but this is still an issue with this library. In SSR mode the server simply doesn't send any cookies which is particularly annoying even if you don't use SSR because it cannot be disabled in dev (afaik).

I figured out a workaround to this issue:

export default defineNuxtPlugin(async (nuxtApp) => {
  const { $apollo } = useNuxtApp();

  $apollo.defaultClient.setLink(
    from([
      new ApolloLink((operation, forward) => {
        operation.setContext(({ headers = {} }) => {
          if (import.meta.server) {
            headers['cookie'] = useRequestHeader('cookie') ?? '';
          }
          return { headers };
        });

        return forward(operation);
      }),
      $apollo.defaultClient.link,
    ])
  );
});

This uses apollo's setLink function to set config values at runtime, import.meta.server to detect if its being run on the server, and Nuxt's useRequestHeader('cookie') to get the cookies of the client's current request.

antonioliv commented 3 months ago

The bug seems to be related to the proxyCookies option in the configuration. It is set to true by default but it isn't working.

Documentation says:

Specify if client cookies should be proxied to the server.

This module provides a proxyCookies option (enabled by default) which when enabled, will proxy all cookies from the client to the server. This is particularly useful for server-side rendering (SSR).

Still no fix to date.

Setting the token.value to something will work and the request will have the cookies for authentication. Here is another workaround for whom is struggling with this:

Create a plugin plugins/apollo.ts with the following:

export default defineNuxtPlugin((nuxtApp) => {
  nuxtApp.hook('apollo:auth', ({ client, token }) => {
    token.value = 'workaround'
  })
})