Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cookies not sent in SSR mode #312

Open
drewbaker opened this issue Feb 23, 2020 · 9 comments · Fixed by #430 · May be fixed by #358
Open

Cookies not sent in SSR mode #312

drewbaker opened this issue Feb 23, 2020 · 9 comments · Fixed by #430 · May be fixed by #358

Comments

@drewbaker
Copy link

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)
@ghost ghost added the cmty:bug-report label Feb 23, 2020
@drewbaker
Copy link
Author

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
Copy link
Author

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
Copy link

rivor commented Oct 2, 2020

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

@hauptbenutzer hauptbenutzer linked a pull request Oct 2, 2020 that will close this issue
@hauptbenutzer
Copy link

@rivor We're currently running with the solution in #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
Copy link

rivor commented Oct 2, 2020

@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
Copy link

kukosek commented Mar 25, 2021

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

@davidhoeck
Copy link

Is there any update on that?

@truesteps
Copy link

truesteps commented Feb 8, 2023

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
Copy link

jf908 commented Mar 19, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

7 participants