Caution in Next.js: The `href` prop does not match between the server and client

I have been using localStorage and useEffect to check the authentication state, and conditionally rendering Navbar items based on the status. However, I encountered an error: Warning: Prop href did not match. Server: "/LoginForm" Client: "/Profile". Can someone please assist me with this issue?

export default function App({Component, pageProps}) {
    const authStorage = typeof window !== "undefined" && localStorage.getItem('isAuth')
    const [isAuth, setAuth] = useState(authStorage ?? null)

    useEffect(() => {
        localStorage.setItem("isAuth", isAuth)
    }, [isAuth])

    return (
        <AppContext.Provider
            value={{
                isAuth,
                setAuth
            }}>
            <Layout>
                <Component {...pageProps} />
            </Layout>
        </AppContext.Provider>
    )
}

export default function Nav() {
    const [visible, setVisible] = useState(false);
    const value = useContext(AppContext);
    const router = useRouter()

    const menuOne = [
        {label: <Link href='/LoginForm'>Log In</Link>, key:'0'},
        {label:<Link href='/RegisterForm'>Sign Up</Link>, key:'1'},
    ]
    const menuTwo=[
        {label: <Link href='/Profile'>Profile</Link>, key:'2'},
        {label:<Link href='/Tickets'>Tickets</Link>, key:'3'},
        {label: <span onClick={Logout}>Logout</span>}
    ]

    return (
        <div className="menu">
            <Link href='/'>
                <div className="logo"/>
            </Link>
            <Menu items={!value.isAuth || value.isAuth === "false" ? menuOne : menuTwo} theme="dark" mode='horizontal' disabledOverflow='true'/>

            <Button className="barsMenu" type="primary" onClick={visible ? onClose : showDrawer}>
                <span className="barsBtn"/>
            </Button>
            <Drawer
                placement="bottom"
                closable={false}
                onClose={onClose}
                open={visible}
                closeIcon
            >
                {!value.isAuth || value.isAuth === 'false' ?
                    (
                        <>
                            <Link href='/LoginForm'>
                                <Button onClick={onClose}>Log in</Button>
                            </Link>
                            <Link href='/RegisterForm'>
                                <Button onClick={onClose}>Sign up</Button>
                            </Link>
                        </>
                    )
                    :
                    (
                        <>
                            <Link href='/Profile' onClick={onClose}>
                                <Button>Profile</Button>
                            </Link>
                            <Link href='/Tickets' onClick={onClose><Button>My tickets</Button></Link>
                            <div className='logout' onClick={Logout}><span onClick={onClose}><Button>logout</Button></span></div>
                        </>
                    )
                }
            </Drawer>
        </div>
    )
}

Answer №1

Here is a simple example that demonstrates the desired behavior of keeping state after refreshing.

_app.js

import { createContext, useContext, useEffect, useState } from "react";
import Nav from "./Nav";

const AppContext = createContext();
export const useAppContext = () => useContext(AppContext);

export default function App({ Component, pageProps }) {
  const [isAuth, setAuth] = useState(false);

  const setAuthAndStore = (bool) => {
    setAuth(bool);
    localStorage.setItem("isAuthenticated", bool);
  }

  useEffect(() => {
    setAuth(localStorage.getItem("isAuthenticated") && localStorage.getItem("isAuthenticated") != "false");
  }, [])

  return (
    <AppContext.Provider
      value={{
        isAuth,
        setAuthAndStore
      }}>

      <Nav />
      <br />
      <Component {...pageProps} />

    </AppContext.Provider>
  )
}

Nav.js

import { useAppContext } from "./_app";

export default function Nav() {
    const { isAuth, setAuthAndStore } = useAppContext();

    return (
        <div className="menu">
            <br />
            <br />

            {!isAuth || isAuth === 'false' ?
                (
                    <>
                        <h1>Please log in to continue</h1>

                        <button onClick={() => {
                            setAuthAndStore(true)
                        }}>Login</button>
                    </>
                )
                :
                (
                    <>
                        <h1>Welcome! You are currently logged in.</h1>

                        <button onClick={() => {
                            setAuthAndStore(false)
                        }}>Logout</button>
                    </>
                )
            }
        </div>

    )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize rest parameters for destructuring操作

I am attempting to destructure a React context using rest parameters within a custom hook. Let's say I have an array of enums and I only want to return the ones passed into the hook. Here is my interface for the context type enum ConfigItem { Some ...

Adding the !important rule in React inline CSS effortlessly

Is there a way to include !important in my inline CSS property without disrupting the entire style? import React from "react"; export default class Todo extends React.Component { render() { const {text} = this.props; const cardStyl ...

Should we integrate sailsjs with reactjs or reactjs with sailsjs? What steps can be taken to achieve this integration?

Currently, I am using SailsJS as my web API and ReactJS for the frontend. Can someone please guide me on how to integrate one into the other seamlessly? I am a beginner in this field, so feel free to highlight any mistakes I may have made. ...

What is the process for retrieving the chosen country code using material-ui-phone-number?

When incorporating user input for phone numbers, I have opted to utilize a package titled material-ui-phone-number. However, the challenge arises when attempting to retrieve the country code to verify if the user has included a 0 after the code. This infor ...

"Uh-oh! Encountered a new unexpected runtime error. Can't seem

While working on my portfolio in Next.js, I encountered an issue. I added a header to display on all pages by placing it in _app.js without making any changes to _document.js. Here is the error message: Unhandled Runtime Error Error: No router instance fo ...

Accessing a New Router with ReactJS

Within my navigation bar, I have implemented an AppRouter using the material-ui library. <NavigationBar> <AppRouter/> </NavigationBar> The structure of my AppRouter is as follows: <Switch> <PublicRoute path="/" compon ...

Text that doesn't appear overwhelming in a Framer Motion text reveal animation

As a newcomer to Framer Motion, I recently attempted to create a Stagger Text effect and a Text Reveal Animation for my portfolio based on various articles. However, despite trying multiple examples, I have encountered an issue where the animation occurs s ...

I desire to perform a specific task when there is a modification in the path using react router framework

Though I am mindful of it. props.history.listen((location, action) => { console.log("when route changes",location); }) However, I need to implement it in a slightly different way. For instance, let's cons ...

Encountering a type error while trying to read dummy data, as the map function is not

I am currently working on fetching dummy data from a URL in my component using TS and Next.js. Unfortunately, I encountered an error type that I am unable to diagnose. typings.d.ts: export type Themen = { id: number; title: string; description: string; ...

Start a websocket server using Next.js (magic server)

I am currently working on developing a Next.js application that involves collaborative editing functionalities. In order to achieve this, my plan is to integrate The TipTap/HocusPocus library. Although I have successfully implemented TipTap in my Next.js ...

What is the best way to combine these two arrays in order to generate the desired JSON structure in a React

Is there a way to transform two arrays like these: const age = [31,53,62] const names = ['john', 'sam', 'kathy'] Into the structure shown below: const data = { "children": [ { "id": 1, "name": "john", "age ...

Using Rust WebAssembly in Next.js

Seeking assistance with integrating a rust-generated wasm module into my NextJS project. This is how I am attempting to import the wasm: import init, { tokenize } from "@/wasm/lazyjson"; const Test = dynamic({ loader: async () => { ...

A problem with the Recharts line chart where the top line is being cut

While my recharts line chart generally works well, it occasionally cuts off the top of the line. Could you please take a look at the code snippet in jsfiddle? const {LineChart, Line, XAxis, YAxis, ReferenceLine, CartesianGrid, Tooltip, Legend} = Recharts; ...

The overflowing issue with the Nextjs Tailwind Marquee Component is causing a display

I've recently developed a unique nextjs/tailwind component. This component displays an isometric marquee that scrolls horizontally. However, I'm facing an issue where the content overflows to the right and causes the page to become horizontally s ...

Is it possible to customize the color of icons in react's Material-table?

I'm currently utilizing the material-table library and I'm struggling to individually change the color of each icon. Could you assist me with this? I attempted custom CSS, but it's affecting all icons at once instead of specific ones. Here i ...

executing Windows Command Prompt commands through package.json scripts

When running commands in the command line (cmd), I have a specific sequence that I need to follow. The first command is 'npm run build' After that, I need to execute: 'xcopy C:\fileOne C:\fileTwo' However, I would like ...

Display a Dialog when a MenuItem is selected

Is there a way to make a Dialog component appear when clicking on a MenuItem within a Material-UI Menu? In my header component, I have the following JSX being returned: return ( <AppBar iconElementLeft={<a href='/'><Avatar src="/st ...

Why is useEffect being executed twice?

For some reason, when I try to run useEffect for the first time page load, it ends up running twice. I can't seem to figure out why this is happening. Can someone please provide assistance? I'm currently using React 18 and I need help understand ...

What steps should I follow to ensure that this table can be sorted efficiently?

I could use some help with this problem. I am new to ReactJS and struggling to implement table sorting based on the clicked column. Do I need to add a class for this? Any assistance would be greatly appreciated. function CreateGradeTable(props) { r ...

What could be causing the error message about undefined classes to appear?

Just started using React and I'm encountering an error with undefined classes. Can someone help me understand why this is happening? Here's the code snippet for reference: const styles = (theme) => ({ root: { width: "100%" ...