Next.js Discord

Discord Forum

Organisation of fetch API (using data from next-auth session)

Unanswered
Northeast Congo Lion posted this in #help-forum
Open in Discord
Northeast Congo LionOP
Hi! I work with Next.js+Strapi project. So far I've been fetching data only on the server side of Next. Because I need to add the Authentication header to each request in case my user is authenticated. The jwt authentication token is stored in session (i use next-auth lib). I have created the following wrapper for fetch (check the bottom of the post) to add the token "in the background".

However, now I need to run some mutation requests from the next client. On the client I can read the session data only using the useSession hook from next-auth. For now I don't have many mutations, so I just write entire fetch() functions in components where these mutations are needed, because I cant find a neat solution to organise it in another way.

The other approach I have thoughts about, is simply to run everything from server side. For this I have to create a route handlers for each mutation. But it seems to have too many elements in this request chain (next client -> next server -> strapi backend)

I'm wondering if someone use a similar stack, or had a similar problem, how have you implemented it?

import 'server-only'

import { getServerSession } from 'next-auth'
import { options as sessionOptions } from '@/app/api/auth/[...nextauth]/options'

const updateOptions = async (options: RequestInit | undefined) => {
const update: RequestInit = options ? JSON.parse(JSON.stringify(options)) : {} //deep copy

const session: any = await getServerSession(sessionOptions)

update.headers = {
...update.headers,
'Content-Type': 'application/json',
}

if (session?.user?.jwt) {
update.headers = {
...update.headers,
Authorization: Bearer ${session.user.jwt},
}
}

return update
}

type Fetcher = typeof fetch

const fetcher: Fetcher = async (url, options) => {
const updatedOptions = await updateOptions(options)

return fetch(${process.env.NEXT_PUBLIC_API_URL}${url}, updatedOptions)
}

export default fetcher

0 Replies