Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next.JS - Access `localStorage` before rendering page

Let's say I have a user's account information stored in localStorage (client side). I need my Next.JS app to render the webpage's navbar based on what's stored in localStorage (login or logout button). How can I first obtain the value from the client and then render the page? Or perhaps that isn't even what Next.JS is meant to do?

like image 688
APixel Visuals Avatar asked Feb 22 '19 03:02

APixel Visuals


People also ask

What is pre-rendering in next JS?

Next. js has two forms of pre-rendering: Static Generation and Server-side Rendering. The difference is in when it generates the HTML for a page. Static Generation is the pre-rendering method that generates the HTML at build time. The pre-rendered HTML is then reused on each request.

Can JavaScript access local storage?

There are four basic JavaScript methods you can use to access and work with localStorage: setItem() - takes a key-value pair and adds it to localStorage. getItem() - takes a key and returns the corresponding value. removeItem() - takes a key and removes the corresponding key-value pair.


1 Answers

You can do something like this:

  1. Use a variable in the state to prevent the page from being rendered
  2. Use componentDidMount to load data from localStorage
  3. When data is loaded, setState to allow component to be rendered.

It's a react issue, not a next.js issue. You could use Conditional rendering for step 1. Also read up on state here, and lastly componentDidMount.

Update:

Nowadays, I would opt for a React hooks implementation instead, but the idea still stands. useEffect can largely accomplish this with some nuances in some situations.

I also realize that there are some possible caveats with NextJS and SSR logic specifically, so this response may not be sufficient. In such cases, I would also look into some other responses below.

like image 118
Keno Avatar answered Sep 27 '22 19:09

Keno