NextJS: Get data from local storage in getInitialProps method

Viewed 7177

I try to migrate my project to Next.js framework for having SSR (Server side rendering) feature. Here is my simple page:

class Example extends React.Component {
  static getInitialProps() {
    // api getting data. Need authentication data under local storage
  }
  render() {
    return <div>{this.props.data}</div>;
  }
}

The problem I met is: I want my data is from getInitialProps first (that is the purpose of SSR). But when sending, I need a information about user for backend API. But at this function, rendering is happened on server so I cannot get data from local storage. How can you solve this problem.

Thanks

2 Answers

You can put the call to localStorage into a react component lifecycle method such as componentDidMount and then setState() with the result.

It's not great, but will work.

Note that this would obviously not use SSR.

This works for me:

const USER = 'user'
const URL = 'http://www.example.com/user'

// here you can also use isServer
if (req) {
    const {data: user} = await Axios.get(URL) 
    localStorage.setItem(USER, JSON.stringify(user))
} else {
    const user = await JSON.parse(localStorage.getItem(USER))
}
Related