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

212
Vistas
Axios instance not working with Nextjs: 'Localstorage not defined'

I have a react app.

I have an axios component I want to reuse:

import axios from 'axios'
import dynamic from 'next/dynamic'    
const baseUrl = 'http://127.0.0.1:8000/'

const axiosInstance = axios.create({
    baseURL: baseUrl,
    timeout: 5000,
    headers: {
        Authorization: localStorage.getItem('access_token')
        ? 'Bearer ' + localStorage.getItem('access_token')
        : null,
        'Content-Type': 'application/json',
        accept: 'application/json',
    }
})

export default axiosInstance

Now, I try and import this into my registration page as follows:

import axiosInstance from "axiosInstance"

The file itself looks like this:

const handleFormSubmit = async (values: any) => {
    axiosInstance.post(`account/register/`, {
      username: values.username,
      email: values.email,
      password: values.password,
      confirm_password: values.confirm_password,
    }).then((response) => {
      console.log(response);
    });

    // router.push('/profile')
    console.log(values);
  };

However, this throws an error:

enter image description here

Can some please help me with this issue? I am new to Nextjs and looked at

https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr

but not sure how to use it in this context.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

localStorage is a propert on window object, and since next.js is a server side rendering framework, when next renders the component on server, window.localStorage will be undefined.

In order to import it, set the axios instance like this:

const axiosInstance = axios.create({
    baseURL: baseUrl,
    timeout: 5000,
    headers: {
        // if localStorage is not defined, it wont throw error
        Authorization:localStorage && localStorage.getItem('access_token')
        ? 'Bearer ' + localStorage.getItem('access_token')
        : null,
        'Content-Type': 'application/json',
        accept: 'application/json',
    }
})

and then inside

about 4 years ago · Juan Pablo Isaza Denunciar

0

localStorage is part of the browser's storage and not the server's. You could use an environment variable and use process.env.ACCESS_TOKEN

More can be read here

Basically you create a file called .env.local There is built in support in NextJS for this file.

Here you defined your variables as follows

ACCESS_TOKEN=myAccessTokenIsAwesome
SOMETHING_ELSE=myOtherKeyINeed

In your code you can then use the process.env.ACCESS_TOKEN to use this defined environment variable

about 4 years ago · Juan Pablo Isaza Denunciar
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