0

I want a component to render based on token is available or not - similar to the jwt localstorage authentication. The issue i found that whenever I refresh the page when the token is available still the component in condition is also flashes or rendered, after that the token condition works and desired component is rendered. My backend is running on another port which is using nodejs express Here is the code.



export default function Home() {
  const [user, setUser] = useState(null);
  const [token, setToken] = useState(null);
  
  useEffect(() => {
    setToken(localStorage.getItem("token"));
}, []);

  useEffect(() => {
    if (token) {
      getuser(token);
    }
  }, [token]);
  const getuser = async (token) => {
    
      const res = await axios.get("http://localhost:5000/result", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      });
      setUser(res.data);
    
  }
  
 


  return (
    <>
      {token ? (
        <>
          <Navbar user={user} />
          <FloatingButton />
        </>
      ) : (
        <>
         <HomePage />
        </>
      )}
    </>
  );
}

I am new in Nextjs and moved from reactjs so i tried ssr in nextjs using getserversideprops but still the issue was not resolved as i found that localstorage can't be accessed through ssr..(i don't know if it is correct or not)

1 Answer 1

0

You obviously can't access localStorage on the server.

I can suggest 2 approaches to this problem:

  1. Render some fallback content in SSR - that's basically what you are currently doing and that's what's causing your UI to flash. To minimize flashing, you can consider rendering empty fallback content if that works in your case.

  2. Store your jwt token in cookies. This way you can read jwt token on the server and dynamically generate pages based on jwt token value. I'd strongly recommend using one of the reputable authentication libraries / providers rather than handcrafting authentication on your own - https://nextjs.org/docs/pages/building-your-application/routing/authenticating#authentication-providers

I hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.