【问题标题】:How to mutate apollo context in next.js?如何在 next.js 中改变 apollo 上下文?
【发布时间】:2020-06-14 21:57:54
【问题描述】:

我查看了api-routes-apollo-server-and-client-auth 示例,但不确定如何在 ssr 和客户端请求中更改上下文。

我希望每个 graphql 解析器(使用 api)都可以使用预解析的 JWT 令牌访问 ctx.user 对象。但是我应该在哪里解析呢?

如果我在这里解析:

const apolloServer = new ApolloServer({
  schema,
  context(ctx) {
    ctx.user = '123'
    return ctx
  }
})

export default apolloServer.createHandler({ path: '/api/graphql' })

然后 ctx.user 将在 SSR 请求上未定义,仅在客户端请求上工作。

【问题讨论】:

    标签: apollo next.js


    【解决方案1】:

    你可以有这样的东西:

    // server
    const apolloServer = new ApolloServer({
      schema,
      context: async () => {
        const jwt = req.headers.authorization
        const user = await getUserFromJwt(jwt)
        return {
          user,
        }
      }
    })
    
    // client
    const link = createHttpLink({ uri: 'http://localhost...' })
    const authLink = setContext((_, { headers }) => {
      return {
        headers: {
          ...headers,
          authorization: jwt,
        },
      }
    })    
    
    const apolloClient = new ApolloClient({
      link: authLink.concat(link),
      ...
    })
    

    查看以下文档:clientserver

    【讨论】:

      猜你喜欢
      • 2023-02-03
      • 2023-02-03
      • 1970-01-01
      • 2020-11-19
      • 2021-09-30
      • 2021-11-08
      • 2017-11-04
      • 2021-11-17
      • 1970-01-01
      相关资源
      最近更新 更多