DEV Community

Nwankwo  Samuel
Nwankwo Samuel

Posted on

Implementing JWT Authentication in React with react-router

JWT (JSON Web Tokens) authentication is a popular method for securing web applications. It allows you to authenticate users and securely transmit information between parties as a JSON object. In this article, we will implement JWT authentication in a React application using react-router for routing.

Prerequisites

Before we begin, make sure you have the following installed:

  • Node.js and npm
  • React
  • react-router-dom

Setting Up the React Application

First, let's create a new React application using Create React App:

npx create-react-app jwt-auth-react
cd jwt-auth-react
Enter fullscreen mode Exit fullscreen mode

Next, install react-router-dom:

npm install react-router-dom
Enter fullscreen mode Exit fullscreen mode

Creating a Login Component

Create a new component for handling user login. This component will send a POST request to your backend to authenticate the user and retrieve a JWT token:

// src/components/Login.js
import React, { useState } from 'react';

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    const response = await fetch('http://your-backend-url/login', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
    });
    const data = await response.json();
    setToken(data.token);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        placeholder="Username"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
      <input
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      />
      <button type="submit">Login</button>
    </form>
  );
};

export default Login;
Enter fullscreen mode Exit fullscreen mode

Creating a Protected Route Component

Next, let's create a ProtectedRoute component that will redirect users to the login page if they are not authenticated:

// src/components/ProtectedRoute.js
import React from 'react';
import { Route, Redirect } from 'react-router-dom';

const ProtectedRoute = ({ component: Component, token, ...rest }) => {
  return (
    <Route
      {...rest}
      render={(props) =>
        token ? <Component {...props} /> : <Redirect to="/login" />
      }
    />
  );
};

export default ProtectedRoute;
Enter fullscreen mode Exit fullscreen mode

Using JWT Authentication in Your App

Now, let's use the Login and ProtectedRoute components in your app:

// src/App.js
import React, { useState } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Login from './components/Login';
import ProtectedRoute from './components/ProtectedRoute';
import Home from './components/Home';

const App = () => {
  const [token, setToken] = useState('');

  return (
    <Router>
      <Switch>
        <Route path="/login">
          <Login setToken={setToken} />
        </Route>
        <ProtectedRoute path="/" exact component={Home} token={token} />
      </Switch>
    </Router>
  );
};

export default App;
Enter fullscreen mode Exit fullscreen mode

In the above code, Home is a placeholder component for your protected content. Replace it with your actual protected component.

Conclusion

JWT authentication is a powerful tool for securing your React applications. By implementing JWT authentication with react-router, you can ensure that only authenticated users have access to certain parts of your application.

Top comments (1)

Collapse
 
nigel447 profile image
nigel447

this code as its written here is not secure