add custom headers using UseSWR * NextJS

Hisinhan / Oct 12 2021

12 mins read • 8,000 views

street crossing in Tokyo

Context:

This is how you normally use UseSWR. I ran into a situation where the API endpoints required authentication header, in order to prevent unlimited API calls.

const fetcher = url => fetch(url).then(r => r.json());

const {data, error} = useSWR(url, fetcher)
if (error) return <NotFoundPage/>
if (!data) return <Loading/>

Solution:

const headersOptions = {
  // your custom header fn()
  headers: () => fn()
}

async function fetcher(url, headers) {
    const response = await fetch(`${url}`, headers)
    return response.json()
}

//👉 USAGE
const {data, error} = useSWR([url, headersOptions], fetcher)
if (error) return <NotFoundPage/>
if (!data) return <Loading/>