Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
How can i create an axios instance on Next.js?

I am trying to create and axios instance so that I don't have to write Authorization header on every request. I am storing access token on localStorage.

I tried creating a file axiosInstance.ts

import axios, { AxiosInstance } from "axios"

 const service = axios.create({
      baseURL: "http://localhost:5000/",
      headers: {
        Authorization: localStorage && localStorage.getItem("token")
          ? `Bearer ${localStorage.getItem("token")}`
          : "",
      },
    })
export default service

But it throws localStorage is not defined error.

So I tried to make this a custom hook like this

useAxios.ts

function useAxios() {
  const [axiosInstance, setAxiosInstance] = useState<null | AxiosInstance>(null)
  useEffect(() => {
    const service = axios.create({
      baseURL: "http://localhost:5000/",
      headers: {
        Authorization: localStorage.getItem("token")
          ? `Bearer ${localStorage.getItem("token")}`
          : "",
      },
    })

    setAxiosInstance(service)
  }, [])

  return axiosInstance
}

export default useAxios

And when i tried to use it like this it threw an error which says service.post is not a function

So when i log the service/axiosInstance it logs a get request promise to baseURL. I am not sure what i am doing wrong.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!