Home » How to use Authentication in Node.js & React?

How to use Authentication in Node.js & React?

How to use Authentication in Node.js & React?

In today’s digital age, the need to authenticate users to grant them secure access to applications is paramount. In this post, we’ll explore setting up authentication in a web application built using Node.js for the backend and React for the frontend.

Table of Contents

  1. Introduction to Authentication
  2. Backend Setup with Node.js
  3. Frontend Authentication with React
  4. Connecting the Dots
  5. Conclusion

1. Introduction to Authentication

Authentication is the process of verifying the identity of a user. For web applications, this typically means collecting a username/email and password and verifying them against stored credentials.

Useful Resources:

2. Backend Setup with Node.js

For the backend, we’ll use Node.js with the Express framework. We’ll also integrate a package called Passport.js, a popular authentication middleware for Node.js.

2.1. Setting Up Express

If you haven’t already set up Express, here’s a guide to get started.

2.2. Integrating Passport.js

  1. Install the required packages:
npm install passport passport-local mongoose express-session
  1. Configure Passport:
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;

passport.use(new LocalStrategy(
  (username, password, done) => {
    // Logic to validate the credentials.
  }
));

2.3. Storing Sessions

Use express-session to store sessions:

const session = require('express-session');

app.use(session({ secret: 'secretKey', resave: false, saveUninitialized: false }));

For a more in-depth look, here’s a tutorial on Passport.js with Express.

3. Frontend Authentication with React

On the frontend, we’ll set up React components to manage our login and registration forms.

3.1. Creating Login and Registration Components

Create two new components: Login.js and Register.js. They will manage the UI and logic for user authentication.

3.2. Protecting Routes

Use react-router-dom to manage routes. Protect certain routes using a higher-order component.

Here’s a guide to protecting routes in React.

4. Connecting the Dots

After setting up the backend and frontend, connect them:

  1. API Calls: Use libraries like axios to make HTTP requests from React to your Node.js server.
  2. Handling Responses: On successful authentication, your backend might send back a token (like a JWT) or a session identifier. Store it using tools like localStorage or cookies.

Here’s a great article that delves into integrating React with a Node.js server.

Examples – Comprehensive Guide

Certainly! Implementing authentication in a Node.js and React application requires quite a bit of setup. Here’s a simple example to demonstrate the concept:

1. Backend (Node.js with Express)

1.1. Basic Setup

Firstly, let’s set up our Node.js application:

mkdir node-auth-backend
cd node-auth-backend
npm init -y
npm install express passport passport-local mongoose bcryptjs express-session

1.2. Model (Using Mongoose)

Create a model User.js:

const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');

const userSchema = new mongoose.Schema({
  username: String,
  password: String
});

userSchema.methods.verifyPassword = function(password) {
  return bcrypt.compareSync(password, this.password);
};

module.exports = mongoose.model('User', userSchema);

1.3. Passport Setup

In your main server file:

const express = require('express');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const session = require('express-session');
const User = require('./User');

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function(err, user) {
      if (err) return done(err);
      if (!user || !user.verifyPassword(password)) return done(null, false);
      return done(null, user);
    });
  }
));

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id, (err, user) => {
    done(err, user);
  });
});

const app = express();
app.use(session({ secret: 'secret', resave: false, saveUninitialized: false }));
app.use(passport.initialize());
app.use(passport.session());

// Your routes here...

app.listen(3000);

2. Frontend (React)

2.1. Basic Setup

Set up your React application:

npx create-react-app react-auth-frontend
cd react-auth-frontend
npm install axios

2.2. Login Component

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

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

  const handleSubmit = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('http://localhost:3000/login', { username, password });
      // Handle response, e.g. save JWT or set user state
    } catch (error) {
      console.error('Login error', error);
    }
  };

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

export default Login;

This is just the tip of the iceberg. In a real-world application, you would need to:

  • Securely handle tokens/JWTs on both the client and server side.
  • Implement registration, password hashing on the server side, and password reset mechanisms.
  • Handle errors and edge cases, set up HTTPS, etc.
  • Implement protected routes in React.

Remember, authentication is a complex topic and requires attention to detail, especially in terms of security.

Conclusion

By now, you should have a clear understanding of setting up authentication in a full-stack application using Node.js and React. While our guide touched on the core parts, remember that authentication is a broad and critical topic.

Another Example is available in video

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Best Coding Ideas in JavaScript

How to create Full Stack Application with Node.js and React ?

Creating a Simple Express.js Server on Node.js

How to authenticate pages in Vuejs (OIDC)

How to use MySQL Database with Node.js?

Setting Up a Node.js Server with Express

Chat Icon