Pass NextAuth JWT to Apollo Client

Viewed 487

I am creating a nextjs app that utilized NextAuth for authentication and the generating of a JWT with custom encode and decode. The custom encode and decode is required for passing hasura claims.

How do I pass that jwt to apollo in order to append the request headers with said jwt so that hasura authenticates my requests? I looked at a few examples where people were pulling their token from ocal storage but NEXTAuth stores the JWT in a cookie. I have no idea how to access it. I have tried adding the token to my session and reading the session with NextAuth getSession() method but it returns null.

lib\apollo.ts

import {
  ApolloClient,
  InMemoryCache,
  ApolloLink,
  HttpLink,
  concat,
} from '@apollo/client'
import { WebSocketLink } from '@apollo/client/link/ws'
import { getSession } from 'next-auth/react'

// TODO - Replace URIs with environment variables

async function sesFunc() {
  const sesh = await getSession()
  return sesh
}
var ses = sesFunc()
console.log(`Session in apollo: ${JSON.stringify(ses)}`)


const graphLink = new HttpLink({
  uri: 'http://localhost:8080/v1/graphql',
})

//GraphQL Relay Endpoint
const relayLink = new HttpLink({
  uri: 'http://localhost:8080/v1beta1/relay',
})

const wsLink =
  typeof window !== 'undefined'
    ? new WebSocketLink({
        uri: 'ws://localhost:8080/v1/graphql',
        options: {
          reconnect: true,
        },
      })
    : undefined
const authMiddleware = new ApolloLink((operation, forward) => {
  //const { data: session, status } = useSession()

  // console.log(`AuthMiddle Session: ${session}`)
  operation.setContext(({ headers = {} }) => ({
    headers: {
      ...headers,
      Authorization:
        'Bearer <token>',
    },
  }))
  return forward(operation)
})

const apolloClient = new ApolloClient({
  link: concat(
    authMiddleware,
    ApolloLink.split(
      (operation) => operation.getContext().clientName === 'relayLink',
      relayLink,
      ApolloLink.split(
        (operation) => operation.getContext().clientName === 'graphLink',
        graphLink,
        wsLink
      )
    )
  ),
  cache: new InMemoryCache(),
})

export default apolloClient

_app.tsx

import '../styles/globals.css'
import type { AppProps } from 'next/app'
import { SessionProvider } from 'next-auth/react'
import IdleTimerContainer from '../components/IdleTimerContainer'
import Layout from '../components/Layout'
import { ApolloProvider } from '@apollo/client'
import apolloClient from '../lib/apollo'

function MyApp({ Component, pageProps: { session, ...pageProps } }: AppProps) {
  return (
    <SessionProvider session={session}>
      <ApolloProvider client={apolloClient}>
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </ApolloProvider>
      <IdleTimerContainer />
    </SessionProvider>
  )
}

export default MyApp
0 Answers
Related