E-commerce
Guide to Creating a Login and Registration Page with Node.js and MongoDB
Guide to Creating a Login and Registration Page with Node.js and MongoDB
If you're developing a web application and need to implement authentication, creating a login and registration page is a crucial step. This guide will walk you through the process using Node.js and MongoDB. We will cover everything from setting up your project to creating the backend and frontend interfaces.
Step 1: Set Up Your Project
Start by creating a new directory and initializing it as a Node.js project. We will use Express for the backend, and MongoDB as our database. Let's set up the basic file structure and install the necessary dependencies.
npx initnpx npm i express mongoose bcryptjs jsonwebtoken body-parser cors dotenv
mkdir my-auth-app
cd my-auth-app
mkdir -p models routes public styles
touch server.js
touch .env
touch models/User.js
touch routes/auth.js
touch
touch
touch styles/styles.css
Step 2: Create the User Model
The User model defines the structure of our user data, including the username and hashed password.
```js // models/User.js const mongoose require('mongoose'); const UserSchema new ({ username: { type: String, required: true, unique: true }, password: { type: String, required: true } }); module.exports ('User', UserSchema); ```Step 3: Set Up Express Server
Configure your Express server to connect to MongoDB and handle incoming requests.
```js // server.js const express require('express'); const mongoose require('mongoose'); const bodyParser require('body-parser'); const cors require('cors'); const User require('./models/User'); const authRoutes require('./routes/auth'); require('dotenv').config(); (_URI, { useNewUrlParser: true, useUnifiedTopology: true }).then(() > console.log('MongoDB connected')) .catch(error > (error)); const app express(); (cors()); (bodyParser.json()); ('/api/auth', authRoutes); const PORT process.env.PORT || 5000; (PORT, () > { console.log(`Server running on port ${PORT}`); }); ```Step 4: Create Authentication Routes
The auth.js file defines the routes for registration and login. We use bcrypt to hash passwords and JSON Web Tokens (JWT) for secure user sessions.
```js // routes/auth.js const express require('express'); const bcrypt require('bcryptjs'); const jwt require('jsonwebtoken'); const User require('../models/User'); const router (); // Register ('/register', async (req, res) > { const { username, password } ; const hashedPassword await bcrypt.hash(password, 10); const user new User({ username, password: hashedPassword }); await (); (201).send('User registered'); }); // Login ('/login', async (req, res) > { const { username, password } ; const user await ({ username }); if (!user) return (400).send('User not found'); const isMatch await (password, ); if (!isMatch) return (400).send('Invalid credentials'); const token ({ id: user._id }, process.env.JWT_SECRET); res.json({ token }); }); module.exports router; ```Step 5: Create HTML Pages
Create the registration and login forms in HTML files located in the public folder.
```html RegisterRegister
registerForm.onsubmit async (e) > { (); const formData new FormData(registerForm); const data (formData); const response await fetch('/api/auth/register', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: (data) }); const result await response.text(); alert(result); } ``` ```html LoginLogin
loginForm.onsubmit async (e) > { (); const formData new FormData(loginForm); const data (formData); const response await fetch('/api/auth/login', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: (data) }); const result await response.json(); alert(`Logged in! : ${result}`); } ```Step 6: Add Basic CSS
A simple CSS file in the styles directory can enhance the user experience of your forms.
```css /* styles/styles.css */ body { font-family: Arial, sans-serif; margin: 20px; } h1 { font-size: 24px; } form { display: flex; flex-direction: column; } input { margin: 10px 0; padding: 10px; } button { padding: 10px; background-color: blue; color: white; border: none; cursor: pointer; } button:hover { background-color: darkblue; } ```Step 7: Environment Variables
Add the necessary environment variables in a .env file at the root of your project.
``` MONGO_URIyour_mongodb_connection_string JWT_SECRETyour_jwt_secret ```Step 8: Run Your Application
Start your server using the following command:
``` bash node server.js ```Open your browser and navigate to /register for the registration page and /login for the login page.
Conclusion
You now have a basic login and registration system using Node.js, Express, MongoDB, and a simple frontend. You can extend this by adding more features such as email verification, password reset, and user profile management as needed.
-
Why Buying Locally Matters: Benefits for Community, Environment, and Individuals
Why Buying Locally Matters: Benefits for Community, Environment, and Individuals
-
Understanding the Comprehensive Landscape of E-commerce: Key Components and Beyond
Understanding the Comprehensive Landscape of E-commerce: Key Components and Beyo