hensei-web/utils/setUserToken.tsx
Justin Edmund a98585a334 Implement setUserToken util function
This function sets axios's default headers to be included before all queries.

We need to call `setUserToken` in _app.tsx so that the defaults are set before every client-side call, and we also need to call it in every instance of `setServerSideProps`.

As a result, wherever we use `getCookies` and construct a `headers` object, we can remove it. Right now, we've only removed it on the top-level pages.
2022-12-22 21:41:38 -08:00

19 lines
565 B
TypeScript

import axios from 'axios'
import { getCookie } from 'cookies-next'
import type { NextApiRequest, NextApiResponse } from 'next'
export default (
req: NextApiRequest | undefined = undefined,
res: NextApiResponse | undefined = undefined
) => {
// Set up cookies
const options = req && res ? { req, res } : {}
const cookie = getCookie('account', options)
if (cookie) {
axios.defaults.headers.common['Authorization'] = `Bearer ${
JSON.parse(cookie as string).token
}`
} else {
delete axios.defaults.headers.common['Authorization']
}
}