New Jan 5, 2025

Page refresh on token-authenticated route redirects to 404 page in React

Libraries, Frameworks, etc. All from Newest questions tagged reactjs - Stack Overflow View Page refresh on token-authenticated route redirects to 404 page in React on stackoverflow.com

I have a simple app where there is a login page and upon submitting the form, it makes a request to the backend which returns a token upon successful authentication, which then redirects to internal dashboard page. There is also another page called settings and another is the NotFound (404) page.

After logging in, when I'm in dashboard page or settings page, if I refresh, it takes me to 404 page whereas it should stay at the page I'm in. Does anybody know what the issue could be?

Here's the code:

App.js

const App = () => { const [isAuthenticated, setIsAuthenticated] = useState(false);

const handleLogin = (token) => { localStorage.setItem('token', token);

setIsAuthenticated(true); };

useEffect(() => { const token = localStorage.getItem('token');

setIsAuthenticated(!!token); }, []);

return ( <Router> { isAuthenticated ? ( <Routes> <Route path="/dashboard" element={ <Layout> <Dashboard /> </Layout> } /> <Route path="/settings" element={ <Layout> <Settings /> </Layout> } /> <Route path="" element={<Layout><NotFound /></Layout>} /> </Routes> ) : ( <Routes> <Route path="/" element={<Login onLogin={handleLogin} />} /> <Route path="" element={<Navigate to="/" />} /> </Routes> ) } </Router> ); }

Login.js

const Login = ({ onLogin }) => {
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const navigate = useNavigate();

    const handleSubmit = async (e) => {
        e.preventDefault();

        const response = await fetch('/api/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username, password }),
        });

        if (response.ok) {
            const result = await response.json();

            if (result.success) {
                localStorage.setItem('token', result.token);

                onLogin(result.token);
                navigate('/dashboard');
            }
        }
    };

    return (
        <div class="container">
            <div class="formContainer">
                <h1>LOGIN</h1>

                <form onSubmit={handleSubmit}>
                    <input
                        type="text"
                        value={username}
                        placeholder="username"
                        onChange={(e) => setUsername(e.target.value)}
                        required
                    />

                    <input
                        type="password"
                        value={password}
                        placeholder="password"
                        onChange={(e) => setPassword(e.target.value)}
                        required
                    />

                    <button type="submit" className="login-button">
                        Login
                    </button>
                </form>
            </div>
        </div>
    );
}
Scroll to top