Implementing JWT Authentication in React with react-router
Tags: webdev, javascript, react, programming
Published: 2024-04-17 20:33:08



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:

```bash
npx create-react-app jwt-auth-react
cd jwt-auth-react
```

Next, install `react-router-dom`:

```bash
npm install react-router-dom
```

## 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:

```jsx
// 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;
```

## 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:

```jsx
// 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;
```

## Using JWT Authentication in Your App

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

```jsx
// 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;
```

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.