I’m trying to set cookies on the client while using Apollo server. Unfortunately I’m unable to set cookies regardless all the alternatives I tried so far. Can someone please help with this issue?
package.json
{
"name": "apollo-graphql",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "ts-node-dev --respawn index.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"apollo-server-express": "^3.6.1",
"cors": "^2.8.5",
"express": "^4.17.2",
"express-session": "^1.17.2",
"graphql": "^16.2.0"
},
"devDependencies": {
"@types/cors": "^2.8.12",
"@types/express": "^4.17.13",
"@types/express-session": "^1.17.4",
"@types/graphql": "^14.5.0",
"ts-node": "^10.4.0",
"ts-node-dev": "^1.1.8",
"typescript": "^4.5.4"
}
}
index.ts
import { ApolloServer, gql } from "apollo-server-express";
import { ApolloServerPluginDrainHttpServer, ApolloServerPluginLandingPageGraphQLPlayground } from "apollo-server-core";
import express from "express";
import http from "http";
import session from "express-session";
import cors from "cors";
async function startApolloServer(typeDefs: any, resolvers: any) {
// Required logic for integrating with Express
const app = express();
const httpServer = http.createServer(app);
app.set("trust proxy", true);
app.use(
session({
name: "qid",
secret: "secretkey",
resave: false,
saveUninitialized: false,
cookie: {
httpOnly: true,
secure: true,
sameSite: "none",
maxAge: 1000 * 60 * 60 * 24 * 365,
},
})
);
app.use(
cors({
credentials: true,
origin: [
"https://studio.apollographql.com",
// "http://localhost:4000/graphql",
],
})
);
// Same ApolloServer initialization as before, plus the drain plugin.
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }: any) => ({ req }),
plugins: [ApolloServerPluginDrainHttpServer({ httpServer }), ApolloServerPluginLandingPageGraphQLPlayground({})],
});
// More required logic for integrating with Express
await server.start();
server.applyMiddleware({
app,
// By default, apollo-server hosts its GraphQL endpoint at the
// server root. However, *other* Apollo Server packages host it at
// /graphql. Optionally provide this to match apollo-server.
path: "/",
});
// Modified server startup
await new Promise<void>((resolve) => httpServer.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
}
const typeDefs = gql`
type Query {
"A simple type for getting started!"
hello: String
}
`;
const resolvers = {
Query: {
hello: () => "What's up world",
},
};
startApolloServer(typeDefs, resolvers);