Sending cookies with Next.js and Axios 🍪
How to send authenticated requests with Next.js and Axios using cookies.
When using Next.js you may need to send authenticated api requests using user
credentials via cookies. The getInitialProps()
method allows us to do this, but the issue
comes when you try to make the requests both server side and client side with
Axios. The context
object that comes with getInitialProps
comes in handy and
can supply the cookie headers when making the request server side. We can use
optional chaining to check whether our request object and headers exist,
otherwise we'll pass undefined. With Axios we can use the
withCredentials: true
option to make this happen with client side requests.
The result looks like this:
Component.getInitialProps = async (ctx) => {
try {
const response = await axios({
method: "get",
url: `http://localhost:3000/api/`,
headers: ctx?.req?.headers?.cookie ? { cookie: ctx.req.headers.cookie } : undefined,
withCredentials: true,
})
return { data: response.data }
} catch (error) {
if (ctx.res) {
console.log(error.message)
ctx.res.writeHead(302, {
Location: "/",
})
ctx.res.end()
}
}
}
I wrapped the Axios get call in a Try...Catch statement to handle any API errors thrown. From there you can choose to redirect the user if the request is made server side.
Have some feedback on this post? .