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:

JavaScript

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

import axiosInstance from "axiosInstance"

The file itself looks like this:

JavaScript

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:

JavaScript

and then inside

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