Skip to content
Advertisement

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.

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement