Search code examples
javascriptsession-cookiesapolloapollo-client

Apollo-Client + Express-Graphql Backend - Session does not persist?


I think I must be not getting something. I am trying to connect my apollo-client localhost:8000 to my backend localhost:4000, with client & server on different domains. I am using apollo (apollo-boost) on the frontend, and express-graphql on the backend (not (!) apollo-server).

When I send some login data from the client to the server, I get back a response: a user object, or errors etc. So that's great. However, the user is never actually logged in on the server (when I check in graphiql and request the user object, it's always null).

I don't know if this is a CORS issue, since things used to work when I had both client & server on the same domain?

Here is the client side code:

import ApolloClient from "apollo-boost"
import fetch from "isomorphic-fetch"
import { HttpLink } from "apollo-link-http"
import { InMemoryCache } from "apollo-cache-inmemory"

const cache = new InMemoryCache()

const link = new HttpLink({
  // uri: "http://localhost:4000/graphql",
  credentials: "include",
})


export const client = new ApolloClient({
  cache,
  fetch,
  link,
  dataIdFromObject: o => o.id,
  uri: "http://localhost:4000/graphql",
})

The relevant bits on the server are:

app.use(
  session({
    resave: true,
    saveUninitialized: true,
    secret: 'whatever',
    cookie: {
      secure: false
    },
    store: new MongoStore({
      url: MONGO_URI,
      autoReconnect: true
    })
  })
);

var corsOptions = {
  origin: 'http://localhost:8000',
  credentials: true
};
app.use(cors(corsOptions));
app.use(passport.initialize());
app.use(passport.session());

// Instruct Express to pass on any request made to the '/graphql' route
// to the GraphQL instance.
app.use(
  '/graphql',
  expressGraphQL({
    schema,
    graphiql: true
  })
);

Solution

  • Seems like their API has changed slightly. I fixed it by doing this on the client side:

    import ApolloClient from "apollo-boost"
    import fetch from "isomorphic-fetch"
    import { InMemoryCache } from "apollo-cache-inmemory"
    
    const cache = new InMemoryCache()
    
    export const client = new ApolloClient({
      cache,
      fetch,
      link,
      credentials: "include",
      dataIdFromObject: o => o.id,
      uri: "http://localhost:4000/graphql",
    })
    

    So I included credentials: "include", right into the Apollo Client, not in the httpLink - actually removed that one.