Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda