789 Views

Creating a web application from scratch may seem challenging for beginners, especially when working with multiple technologies. This node js bootstrap tutorial will guide you through building a basic registration app using Node.js, Bootstrap, and MongoDB. Along the way, you’ll see how these pieces fit together to bring a real, working web app to life.

Prerequisites

Before starting, ensure you have the following installed on your system:

  • Node.js and npm: Download and install from the official website.
  • MongoDB: Install from the MongoDB website or use a cloud service like MongoDB Atlas.
  • Basic Knowledge: Familiarity with JavaScript, HTML, and CSS is beneficial.

Setting Up the Project

Initialize the Project Directory

Create a new directory for your project and navigate into it:

mkdir beginner-app
cd beginner-app

Initialize the project with npm:

npm init -y

This command generates a package.json file with default settings.

Install Necessary Dependencies

We’ll use several packages for this node js bootstrap tutorial:

  • Express: Web application framework for Node.js.
  • Mongoose: Object Data Modeling (ODM) library for MongoDB.
  • Pug: Template engine for rendering dynamic content.
  • Express-Validator: Middleware for validating and sanitizing user input.
  • Express-Basic-Auth: Middleware for basic HTTP authentication.
  • Dotenv: Module to load environment variables.
  • Nodemon: Utility that automatically restarts the server.

Install these packages using npm:

npm install express mongoose pug express-validator express-basic-auth dotenv
npm install --save-dev nodemon

Setting Up the Server

Node JS Bootstrap Tutorial with MongoDB Build Dynamic Web Apps

Create the Entry Point

For this step of the node js bootstrap tutorial, you’ll need to create a new file called app.js. Once you have it, go ahead and drop in the following code:

const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
// Connect to MongoDB
mongoose.connect(process.env.DATABASE_URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
mongoose.connection
  .on('connected', () => {
    console.log('Connected to MongoDB');
  })
  .on('error', (err) => {
    console.error(`Database error: ${err.message}`);
  });
// Set up Pug as the template engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// Middleware to parse URL-encoded bodies
app.use(express.urlencoded({ extended: true }));
// Serve static files
app.use(express.static(path.join(__dirname, 'public')));
// Routes
const indexRouter = require('./routes/index');
app.use('/', indexRouter);
module.exports = app;

Start the Server

In the next step of our node js bootstrap tutorial, create start.js to initialize the server:

const app = require('./app');
const server = app.listen(3000, () => {
  console.log(`Server running on port ${server.address().port}`);
});

Great! Using a .env file helps keep sensitive information, like database URLs or API keys, out of your code. Let’s set one up to safely store environment variables for your project. In your project’s root directory, create a new file named .env. Inside, add the following:

DATABASE_URL=mongodb://localhost:27017/beginner-app

Make sure to add .env to your .gitignore file to keep sensitive information safe.

Creating the Data Model

Create a models directory and add User.js:

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: 'Name is required',
    trim: true,
  },
  email: {
    type: String,
    required: 'Email is required',
    trim: true,
  },
});
module.exports = mongoose.model('User', userSchema);

Require the model in app.js:

require('./models/User');

Setting Up Routes

Create a routes directory with index.js:

const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const { check, validationResult } = require('express-validator');
const User = mongoose.model('User');
// GET registration form
router.get('/', (req, res) => {
  res.render('form', { title: 'Registration Form' });
});
// POST form submission
router.post(
  '/',
  [
    check('name').notEmpty().withMessage('Name is required'),
    check('email').isEmail().withMessage('Valid email is required'),
  ],
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.render('form', {
        title: 'Registration Form',
        errors: errors.array(),
        data: req.body,
      });
    }
    const user = new User(req.body);
    user
      .save()
      .then(() => res.render('success', { title: 'Registration Successful' }))
      .catch((err) => {
        console.error(err);
        res.send('An error occurred while saving data.');
      });
  }
);
// GET user list with authentication
router.get('/users', (req, res) => {
  User.find()
    .then((users) => {
      res.render('users', { title: 'User List', users });
    })
    .catch(() => res.send('Error fetching users'));
});
module.exports = router;

Designing Views with Pug

For this node js bootstrap tutorial, we’ll create the necessary views using Pug. Start by creating a views directory.

First, create views/layout.pug, which will serve as the base layout for our pages:

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/css/bootstrap.min.css')
    link(rel='stylesheet', href='/css/styles.css')
  body
    .container
      h1.text-center.mt-5 Beginner Registration App
      block content

Next, create views/form.pug for the registration form:

extends layout
block content
  if errors
    ul.text-danger
      each error in errors
        li= error.msg
  form(method='POST', action='/')
    .mb-3
      label(for='name' class='form-label') Name:
      input#name.form-control(
        type='text',
        name='name',
        required,
        value=data ? data.name : ''
      )
    .mb-3
      label(for='email' class='form-label') Email:
      input#email.form-control(
        type='email',
        name='email',
        required,
        value=data ? data.email : ''
      )
    button.btn.btn-primary(type='submit') Register

Create views/success.pug for the success message after registration:

extends layout
block content
  h2.text-center.mt-5 Registration Successful!

Finally, create views/users.pug to display the list of registered users:

extends layout
block content
  h2.text-center.mt-5 Registered Users
  if users.length
    table.table.table-striped.mt-3
      thead
        tr
          th Name
          th Email
      tbody
        each user in users
          tr
            td= user.name
            td= user.email
  else
    p.text-center No users found.

Adding Bootstrap and Custom Styles

Node JS Bootstrap Tutorial with MongoDB Build Dynamic Web Apps

Download Bootstrap and place bootstrap.min.css in public/css/. Alternatively, use a CDN link in your layout template. This step helps ensure your node js bootstrap tutorial app looks professional and well-designed.

Create public/css/styles.css:

body {
  padding-top: 50px;
}
.container {
  max-width: 600px;
}
.text-danger {
  list-style-type: none;
  padding: 0;
}

Implementing Basic Authentication

Install express-basic-auth:

npm install express-basic-auth

In app.js, add the authentication middleware:

const basicAuth = require('express-basic-auth');
app.use(
  '/users',
  basicAuth({
    users: { admin: 'password' },
    challenge: true,
  })
);

This addition to the node js bootstrap tutorial secures the user list route.

Running the Application

Add a script to package.json:

"scripts": {
  "start": "nodemon start.js"
}

Start the application:

npm start

Visit http://localhost:3000 to access the registration form. After submitting data, navigate to http://localhost:3000/users and log in with the credentials admin and password.

Conclusion

This node js bootstrap tutorial has guided you through creating a simple web application using Node.js, Bootstrap, and MongoDB. By building this app, you’ve learned how to set up a Node.js server, create dynamic views with Pug, handle form data and validation, interact with a MongoDB database, and implement basic authentication. These foundational skills are essential for any web developer looking to expand their expertise.

FAQ

1. Why use Node.js with Bootstrap and MongoDB?

Node.js allows for server-side JavaScript execution, enabling full-stack development with a single language. Bootstrap provides a responsive design framework, and MongoDB offers a flexible NoSQL database solution. Together, they create a powerful stack for web development.

2. How does this node js bootstrap tutorial help beginners?

This tutorial breaks down the development process into manageable steps, making it easier for beginners to understand how different technologies integrate to form a complete application.

3. Can I use a different templating engine instead of Pug?

Yes, you can use other templating engines like EJS or Handlebars. Adjust the code accordingly if you choose to switch.

4. Is MongoDB the only database option for Node.js applications?

No, Node.js supports various databases like MySQL, PostgreSQL, and SQLite. MongoDB is used in this tutorial for its simplicity and flexibility.

5. How can I deploy this application to a live server?

You can deploy the app using services like Heroku, AWS, or DigitalOcean. Ensure that your database is accessible and that environment variables are properly configured.

6. What are some next steps after completing this node js bootstrap tutorial?

Consider adding user authentication with JWT, implementing password hashing, or integrating a frontend framework like React or Vue.js for a more dynamic user experience.

7. How do I handle errors more effectively in the application?

Implement comprehensive error handling by adding middleware to catch and respond to errors gracefully, improving the application’s robustness.

8. Can I use a CSS framework other than Bootstrap?

Yes, you can use frameworks like Tailwind CSS or Bulma. Replace Bootstrap links and classes with those from your chosen framework.

9. How do I ensure the application is secure?

Keep dependencies updated, validate and sanitize all user inputs, use HTTPS in production, and consider security-focused middleware and practices.

10. Where can I learn more about Node.js and related technologies?

Visit the official documentation for Node.js, Express, and MongoDB. Online courses and tutorials can also provide in-depth knowledge.