Home > Enterprise >  Axios instance not working with Nextjs: 'Localstorage not defined'
Axios instance not working with Nextjs: 'Localstorage not defined'

Time:10-01

I have a react app.

I have an axis 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 around 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.

CodePudding user response:

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

CodePudding user response:

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

  • Related