Next.js Discord

Discord Forum

openapi-fetch authentication

Unanswered
European pilchard posted this in #help-forum
Open in Discord
European pilchardOP
I'm using openapi-ts and openapi-fetch to somes types and a fetcher on my Next.js v13.4.8 app using App Router, but I'm having a hard time adapting the openapi-fetch example to my needs : https://openapi-ts.pages.dev/openapi-fetch/examples/

The thing I can't quite grasp is how implement the someAuthMethod()on my / src/lib/api/index.tsfile.
I have tried using getServerSession from next-auth, but keep getting this error "Invariant: Method expects to have requestAsyncStorage, none available".

My code is the following :

// src/lib/api/index.ts
import createClient from 'openapi-fetch'
import { paths } from './v1'
import { getServerSession } from 'next-auth'
import { authOptions } from '../auth'

const getAuthToken = async () => {
  const session = await getServerSession(authOptions)
  return session?.user?.accessToken
}

let authToken: string | undefined = undefined

await getAuthToken().then((newToken) => (authToken = newToken))

const baseClient = createClient<paths>({
  baseUrl: process.env.NEXT_PUBLIC_BACKEND_API_URL,
})

const proxy = new Proxy(baseClient, {
  get(_, key: keyof typeof baseClient) {
    const newClient = createClient<paths>({
      headers: authToken ? { Authorization: `Bearer ${authToken}` } : {},
      baseUrl: process.env.NEXT_PUBLIC_BACKEND_API_URL,
    })
    return newClient[key]
  },
})

export default proxy
`

import { authOptions } from '@/lib/auth'
import { getServerSession } from 'next-auth/next'
import { columns, LeadsTable } from '@/components/LeadsTable'
import client from '@/lib/api'

async function getWantedLeads() {
  return await client.GET('/leads')
}

export default async function Wishlist() {
  const session = await getServerSession(authOptions)
  const { data: leads, error } = await getWantedLeads()
  return session ? (
      {leads?.error ? <p>Error</p> : <LeadsTable columns={columns} data={leads} />}
}


Anyone has an idea what I'm missing ? 🙂

0 Replies