-
Notifications
You must be signed in to change notification settings - Fork 2.7k
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
Apollo Client does not pass cookies #4190
Comments
I am using following dependencies
|
I have the same issue with apolloboost the cookies not sent with the request |
Same here |
Same here, anyone have any luck with this? |
I think you need to verify your server the issue for me was the cors i was passing cors options in the wrong place now it works as expected |
@serendipity1004 works here. Doesn't it work during SSR or on client side? |
Figured it out.
I was using inside of |
I'm pretty sure I'm still having this issue. My rest calls have cookies attached, however my graphql queries don't. |
I'm having a similar problem, but I actually think it is a browser issue and nothing to do with the Apollo Client. When I have my front-end hosted on Heroku like It seems to me, the browser considers any cookie from different subdomain's to be 3rd party. There are varying degrees of this: Opera - Cookies blocked if "Block Third Party Cookies" enabled |
Hi, I found that when I want to make request with "Cookie" then apollo client is not sending it, but just when I change it to "Cookies" then everything is ok XD |
Hi there, I'm still having the issue here. I'm working with:
withCredentials is sets to true in my apollo.config.ts file:
Is there anybody that can tell us why ? |
@rrakso Did you mean like this?
|
Anyone have any further insight? |
@TheoMer yup ;) |
@rrakso Could you provide a snippet of what is working for you? |
i'm using
|
This also fixed my issue, the docs are a bit confusing as credentials: 'include' is nested under fetchOptions; putting in the root fixed my issue. Is there a reason why this option can be put in two places? Only the root worked for me and caused a lot of confusion |
FYI: I'm using fetch, and axios, thats what's not setting the cookie header for me. |
I had to do this for our build a few days ago, here is how I did it - https://gist.github.com/neil-gebbie-smarterley/cd8356df4c786c4c9dacfc9d46e890ac Our set it is: It's basically just passing it through to the server, I'm not sure if the document.cookie is needed for subsequent requests, but it seems to be working ok for us, not in production yet, but it's passing cookies. |
Oddly enough, what worked for me was to set an AuthLink with
I'm not sure if this is a good workaround (maybe dangerous?); you'll be bombarded with reference errors as localStorage is not available when NextJS renders in server-side. Edit: Eh...doesn't work on mobile. |
This works for me:
|
Put the
Then put that in your ApolloClient. Worked finally without a bunch of custom stuff. |
I've fixed it for myself using the latest libraries [email protected], [email protected] and [email protected]. Cookies are passed with every request, SSR working as expected and no errors. Code is here. I had to remove |
@RiChrisMurphy I'm seeing a similar issue. Were you able to find a fix for that? |
@helfi92 Have you tried any of the solutions in this thread? |
I think I understand what's happening. The client and server I'm working with are both subdomains of herokuapp (e.g..,
Using a custom domain will probably resolve the issue. |
I've been trying in Razzle to no avail. Cookies are passed to playground very ok, but on razzle it's not |
@juicycleff What does your createApolloClient file look like? Do you have a withApolloClient HOC? |
Hello @cyc1e from 2021 - we have been using my this in production since 2020, see the gist above for the implementation. |
I ended up using Axios to make my queries. Its a hell of a learning curve using axios to run graph queries but now I have a product that works and businesses are using it :) To be honest rest would have been way easier and quicker but we implemented graph in our back-end and pushed through with it. Its time consuming. |
There is a lot of history in this issue, and the problems listed head in all sorts of different directions. If anyone thinks this is still a problem in |
Hi guys, same problem. It works in browser, but not on server side. @apollo/client ^3.0.2 Apollo client credentials: const { HttpLink } = require('@apollo/client/link/http')
return new HttpLink({
uri: 'http://localhost:3000/api/graphql',
credentials: 'same-origin',
}) I can read the cookies in |
I'm using this example, you may use that to reproduce as it has the same issue. https://github.com/vercel/next.js/tree/canary/examples/api-routes-apollo-server-and-client-auth Try to use I hope it helps. |
@allanesquina |
@hwillson I did some tests and I realized that the return new SchemaLink({ schema, context: { { req, res } }) So I'm passing the context all way down in export async function getServerSideProps(context) {
const client = initializeApollo(null, context);
...
} The client.js file import { useMemo } from "react";
import { ApolloClient, InMemoryCache } from "@apollo/client";
import merge from "deepmerge";
let apolloClient;
function createIsomorphLink(ctx) {
if (typeof window === "undefined") {
const { SchemaLink } = require("@apollo/client/link/schema");
const { schema } = require("./schema");
return new SchemaLink({ schema, context: ctx });
} else {
const { HttpLink } = require("@apollo/client/link/http");
return new HttpLink({
uri: "/api/graphql",
credentials: "same-origin",
});
}
}
function createApolloClient(ctx) {
return new ApolloClient({
ssrMode: typeof window === "undefined",
link: createIsomorphLink(ctx),
cache: new InMemoryCache(),
});
}
export function initializeApollo(initialState = null, ctx) {
const _apolloClient = apolloClient ?? createApolloClient(ctx);
// If your page has Next.js data fetching methods that use Apollo Client, the initial state
// get hydrated here
if (initialState) {
// Get existing cache, loaded during client side data fetching
const existingCache = _apolloClient.extract();
// Merge the existing cache into data passed from getStaticProps/getServerSideProps
const data = merge(initialState, existingCache);
// Restore the cache with the merged data
_apolloClient.cache.restore(data);
}
// For SSG and SSR always create a new Apollo Client
if (typeof window === "undefined") return _apolloClient;
// Create the Apollo Client once in the client
if (!apolloClient) apolloClient = _apolloClient;
return _apolloClient;
}
export function useApollo(initialState) {
const store = useMemo(() => initializeApollo(initialState), [initialState]);
return store;
} It solves the issue using the Just an update: I'm using |
Heyo! I was running into the issue of apollo-client sending / setting cookies client side fine, but was getting problems with it server side. I use an afterware server-side to set cookies. Here's my fix with typescript: import {
ApolloClient, ApolloLink, HttpLink, InMemoryCache, gql,
} from '@apollo/client';
import { NormalizedCacheObject } from '@apollo/client/cache';
import { GetServerSidePropsContext } from 'next';
import { useMemo } from 'react';
const createClient = (ctx?: GetServerSidePropsContext) => {
const setCookiesAfterware = new ApolloLink((operation, forward) => forward(operation).map((response) => {
ctx?.res.setHeader('set-cookie', operation.getContext().response.headers.raw()['set-cookie'] || '');
return response;
}));
return new ApolloClient({
link: setCookiesAfterware.concat(new HttpLink({ uri: 'http://localhost/graphql', headers: { cookie: ctx.req.headers.cookie } })),
cache: new InMemoryCache(),
});
};
let client: ApolloClient<NormalizedCacheObject> | undefined;
const initializeClient = (initialState?: NormalizedCacheObject, ctx?: GetServerSidePropsContext) => {
const apolloClient = client ?? createClient(ctx);
if (initialState) {
const prevState = apolloClient.extract();
apolloClient.restore({ ...prevState, ...initialState, ...{ ROOT_QUERY: { ...prevState.ROOT_QUERY, ...initialState.ROOT_QUERY } } });
}
if (typeof window === 'undefined') return apolloClient;
client ??= apolloClient;
return client;
};
const useClient = (initialState?: NormalizedCacheObject) => useMemo(() => initializeClient(initialState), [initialState]);
const getClient = (ctx: GetServerSidePropsContext) => initializeClient(undefined, ctx);
export { gql, useClient };
export default getClient; |
Thx @rag4214, now it made sense, I have to set the headers to forward the cookies to the API. |
This worked for me. Thanks @rag4214 |
Add cookie to getServerSideProps on a page by page basisEasy quick method to add cookie is to pass context.
If client side is not storing cookie on login or whateveradding credentials property seems to do the trick
The docs are here: |
@gregg-cbs I believe this is what we want to avoid (although this is what I do now). Repetitive code in many pages is a bad practice. Need to find a solution for this. |
@alanyong91 We definitely want cookies to be something that happens naturally. What solutions can you think of that would be good to try? I think together as a community we can come up with an ideal solution and if not make it ourselves we can propose it to next and or apollo. |
Guys the problem that we are new to Next.js or any SSR (server side rendering) you guys are using. |
This is example with nextjs apollo ssr codegen, const {
props: { apolloState, data, error },
} = await ssrGetOwnSettings.getServerPage(
{ variables: { where: { id } } },
context,
); initiate client, const createApolloClient = (context: Context) => {
return new ApolloClient({
cache: new InMemoryCache(),
connectToDevTools: isDevelopment,
ssrMode: typeof window === 'undefined',
link: createHttpLink({
uri: `${appConfig.baseUrl}${appConfig.apiUrl}`,
headers: { cookie: context?.req?.headers.cookie },
}),
});
}; |
I try almost everything, but it still doesn't work for me... I can only making work with httponly = false cookie :
If I try to add credentials:"include" to my httpLink, I get : The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. I setup my cookie using /api/login
|
@Kaherdin yes, that's an HTTP security limitation—your server can't send the wildcard One solution (not the most secure) is to pass app.use(cors({
credentials: true,
// allow all origins
origin: true,
})) The more secure way is to check the origin against a whitelist, as explained here: I also found that in my case, since I'm using const corsOptions = {
credentials: true,
// allow all origins
origin: true,
}
apolloServer.applyMiddleware({
app: server,
cors: corsOptions,
}) |
In my case I was using a custom
|
@dclipca FYI I think that because you're using a custom link, the second |
My problem was with Apollo Studio. Solution for me was a combination of the following. index.ts (in apollo server):
In resolver response that sets the token:
Studio Settings: |
For a bit more context, I'm experiencing this specifically in Safari (15.5), w/ "Prevent cross-site tracking" enabled, while doing local development on http://myapp.local. My GraphQL API is served from the domain http://api.myapp.local. The cookies are assigned the domain Doing either of the following DOES work:
I realize a number of the comments on this issue are likely about diverging issues, with many being simply misconfiguration issues. But I suspect a number of people are experiencing this issue due to some combination of issues with Safari's cookie protection, sub-domains, and maybe Apollo itself? |
I had a similar kind of issue where cookies were not being sent along with all the requests even tho cookies were stored in the browser. On localhost everything was working fine but things were different for staging environment since the staging frontend and backend urls were comprised of different subdomains and for cookie to be available I had to setup domain and path in cookie explicitly Suppose your frontend and backend url are like these
|
@huzaifaali14 it has already been written here many times |
I had the same problem. My solution was the following (I did not find a place where I could clarify it, but it was a trial and error) Apollo client config: import {ApolloClient, HttpLink, InMemoryCache} from "@apollo/client";
const httpLink = new HttpLink({
uri: `${process.env.NEXT_PUBLIC_URL_SITE}/api/graphql`,
credentials: "same-origin",
});
export const client = new ApolloClient({
link: httpLink,
cache: new InMemoryCache(),
});
SSR request (typescript): export const getServerSideProps: GetServerSideProps = async ({req}) => {
const {data} = await client.query({
query: QUERY_NAME,
context: {
headers: {
cookie: req?.headers?.cookie ?? null,
},
},
});
return {
props: {data},
};
}; I'm using:
|
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. |
I am currently using nextJS with apollo and it's completely unusable for me because the cookie is not passing in every request.
I would be much grateful if someone can just point me to right direction to pass cookies properly.
Even the apollo nextjs example is buggy itself https://github.com/adamsoffer/next-apollo-example
Even in that example, cookies are not being sent in the request.
I am trying every possible way of setting cookies in config without success.
Some people say swapping ApolloClient to ApolloBoost have solved it but neither of the packages work for me.
Below is an example of what I have tried
The text was updated successfully, but these errors were encountered: