Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
913 views
in Technique[技术] by (71.8m points)

javascript - How to setup CORS and Cookie properly in Next.js with Apollo client and Apollo server Koa?

I have this Next.js app with Apollo client, and I use apollo-server-koa with koa-session for API.

Configs for @koa/cors and koa-session:

// app.ts

export const app = new Koa()
app.keys = ['secret']

app.use(cors({
  credentials: true,
}))
app.use(session({
  key: 'foobar',
  secure: NODE_ENV === 'production' ? true : false,
}, app))

In Next.js, this is the apolloClient config:

function createApolloClient() {
  return new ApolloClient({
    ssrMode: typeof window === 'undefined',
    link: new HttpLink({
      uri: 'http://localhost:8000/graphql', // Server URL (must be absolute)
      credentials: 'include', // Additional fetch() options like `credentials` or `headers`. Default is `same-origin`
    }),
    cache: new InMemoryCache(),
  })
}

When I sign in (mutation) at http://localhost:3000/auth from Next.js app, server (http://localhost:8000/graphql) successfully sets cookie in the browser. However, Next.js does not send cookie back to server.

Please help me, what I am doing wrong?

@koa/cors: https://github.com/koajs/cors
koa-session: https://github.com/koajs/session
apollo-client auth: https://www.apollographql.com/docs/react/networking/authentication/#cookie


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...