,

Node.js User Authentication using Express.js #node #express #authentication

Posted by


User authentication is an essential feature for any web application that requires user-specific data or actions. In this tutorial, we will go through the process of setting up user authentication using Node.js and Express.js.

Step 1: Setting up your project
First, you need to create a new Node.js project and install Express.js by running the following commands in your terminal:

mkdir user-authentication
cd user-authentication
npm init -y
npm install express

Step 2: Creating a user model
Next, you need to create a user model to store user information in your application. Create a new file called models/user.js and add the following code:

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
  username: { type: String, required: true },
  password: { type: String, required: true }
});
module.exports = mongoose.model('User', userSchema);

Step 3: Setting up MongoDB
You will need to have MongoDB installed on your machine. You can download and install MongoDB from the official website. Once you have MongoDB installed, you need to connect your Node.js application to the MongoDB database. Create a new file called db.js and add the following code:

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/user-authentication', { useNewUrlParser: true, useUnifiedTopology: true });

Step 4: Creating routes for user authentication
Create a new file called routes/auth.js and add the following code:

const express = require('express');
const router = express.Router();
const User = require('../models/user');
router.post('/register', async (req, res) => {
  const { username, password } = req.body;
  const user = new User({ username, password });
  await user.save();
  res.json({ message: 'User registered successfully' });
});
module.exports = router;

Step 5: Setting up user authentication middleware
Create a new file called middleware/auth.js and add the following code:

const User = require('../models/user');
const auth = async (req, res, next) => {
  const { username, password } = req.body;
  const user = await User.findOne({ username, password });
  if (!user) {
    return res.status(401).json({ message: 'Authentication failed' });
  }
  req.user = user;
  next();
};
module.exports = auth;

Step 6: Protecting routes with authentication middleware
Now you can protect your routes by adding the authentication middleware to them. For example, create a new file called routes/dashboard.js and add the following code:

const express = require('express');
const router = express.Router();
const auth = require('../middleware/auth');
router.get('/dashboard', auth, (req, res) => {
  res.json({ message: 'Welcome to the dashboard' });
});
module.exports = router;

Step 7: Setting up your server
Finally, create a new file called index.js and add the following code to set up your server:

const express = require('express');
const app = express();
const db = require('./db');
app.use(express.json());
app.use('/auth', require('./routes/auth'));
app.use('/dashboard', require('./routes/dashboard'));
const PORT = 3000;
app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});

Now you have a basic user authentication system set up in your Node.js and Express.js application. You can expand on this tutorial by adding features like password hashing, form validation, and error handling. Remember to always handle user authentication securely to protect your users’ data.

0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x