I developed a GraphQL server using apollo-server-express
, and it is currently running on localhost:4000.
Upon sending a query from GraphQL playground, the response includes a set-cookie in the header: response header
However, when checking the storage > cookies tab in Chrome, no cookies are found. chrome: application > storage > cookies
Below is my server.ts file. (I believe I have configured my cors
settings correctly)
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: true,
playground: true,
dataSources: () => ({
projectAPI: new ProjectAPI(),
}),
context: ({ req, res }: { req: Request; res: Response }) => ({ req, res }),
})
const app = express()
/* Parse cookie header and populate req.cookies */
app.use(cookieParser())
app.use(
cors({
origin: '*',
credentials: true, // <-- REQUIRED backend setting
})
)
app.use((req: any, res: any, next: any) => {
console.log(req.cookies)
next()
})
server.applyMiddleware({ app, path: '/' })
if (process.env.NODE_ENV !== 'test') {
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
)
}
export { server }
Furthermore, here is my resolvers.ts
:
export default {
Query: {
session: async (_: null | undefined, __: null | undefined, { res }: any) => {
const response = await fetch(`http://localhost:3000/api/v1/sessions/current_user`, {
headers: {
'content-type': 'application/json',
},
})
/** Obtain session cookie from the response header */
const sessionCookie = setCookie
.parse(response.headers.get('set-cookie') as string)
.find((el: any) => el.name === '_session')
/** If session cookie exists, store the cookie */
if (sessionCookie && res) {
const { name, value, ...rest } = sessionCookie
res.cookie(name, value, rest)
}
const data = await response.json()
return data.user
},