Node JS Tutorial: Backend Development for Beginners - Complete Guide 2026
Node.js has transformed backend development by allowing JavaScript to run on the server. This Node.js tutorial for beginners covers everything you need to start building server-side applications in 2026, from installing Node.js to building complete REST APIs with authentication and database integration.
What Is Node.js and Why Learn It in 2026
Node.js is a JavaScript runtime built on Chrome's V8 JavaScript engine that executes JavaScript code outside the browser. This enables developers to use a single language (JavaScript) for both front-end and back-end development.
Node.js is used by companies like Netflix, LinkedIn, Uber, and PayPal to build scalable network applications. Learning Node.js opens career paths in full stack development, backend engineering, and API development.
Why Node.js Dominates Backend Development in India 2026
- One language for the entire stack (JavaScript)
- Largest ecosystem of packages (npm) with over 2 million libraries
- Excellent for building real-time applications (chat, live updates)
- High performance due to non-blocking I/O
- Strong job market across startups, agencies, and enterprise companies
- Perfect foundation for learning Express.js and building MERN stack applications
Installing and Setting Up Node.js
```bash
# Download and install Node.js from nodejs.org
# Choose the LTS (Long Term Support) version
# Verify installation
node --version # Should show v20.x or higher
npm --version # Should show 10.x or higher
# Create a new project
mkdir my-node-api
cd my-node-api
npm init -y
# Install Express.js (most popular Node.js framework)
npm install express
# Install nodemon for automatic server restart during development
npm install --save-dev nodemon
# Create a start script in package.json
# Add: "scripts": { "dev": "nodemon index.js" }
```
Your package.json should look like:
```json
{
"name": "my-node-api",
"version": "1.0.0",
"description": "REST API with Node.js and Express",
"main": "index.js",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
},
"dependencies": {
"express": "^4.18.2"
}
}
```
Creating Your First Node.js Server
```javascript
// index.js
const express = require('express')
const app = express()
const PORT = process.env.PORT || 3000
// Middleware to parse JSON request bodies
app.use(express.json())
// Sample data (in real apps, use a database)
const courses = [
{ id: 1, title: 'React JS Tutorial', slug: 'react-js-tutorial', category: 'Frontend' },
{ id: 2, title: 'Node JS Tutorial', slug: 'node-js-tutorial', category: 'Backend' },
{ id: 3, title: 'MongoDB Tutorial', slug: 'mongodb-tutorial', category: 'Database' }
]
// Root route
app.get('/', (req, res) => {
res.json({
message: 'Welcome to Node.js API',
version: '1.0.0',
endpoints: {
courses: '/api/courses',
blog: '/api/blog'
}
})
})
// GET all courses
app.get('/api/courses', (req, res) => {
res.json({
success: true,
count: courses.length,
data: courses
})
})
// GET single course by ID
app.get('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) {
return res.status(404).json({
success: false,
message: 'Course not found'
})
}
res.json({
success: true,
data: course
})
})
// POST - Create new course
app.post('/api/courses', (req, res) => {
const { title, slug, category } = req.body
if (!title || !slug) {
return res.status(400).json({
success: false,
message: 'Title and slug are required'
})
}
const newCourse = {
id: courses.length + 1,
title,
slug,
category: category || 'General'
}
courses.push(newCourse)
res.status(201).json({
success: true,
message: 'Course created successfully',
data: newCourse
})
})
// PUT - Update course
app.put('/api/courses/:id', (req, res) => {
const course = courses.find(c => c.id === parseInt(req.params.id))
if (!course) {
return res.status(404).json({
success: false,
message: 'Course not found'
})
}
const { title, category } = req.body
if (title) course.title = title
if (category) course.category = category
res.json({
success: true,
message: 'Course updated successfully',
data: course
})
})
// DELETE - Remove course
app.delete('/api/courses/:id', (req, res) => {
const courseIndex = courses.findIndex(c => c.id === parseInt(req.params.id))
if (courseIndex === -1) {
return res.status(404).json({
success: false,
message: 'Course not found'
})
}
const deletedCourse = courses.splice(courseIndex, 1)[0]
res.json({
success: true,
message: 'Course deleted successfully',
data: deletedCourse
})
})
// Start the server
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`)
console.log('Node.js Tutorial API is ready!')
})
```
Run the server with:
```bash
npm run dev
```
Test your API with curl or a tool like Postman:
```bash
# Get all courses
curl http://localhost:3000/api/courses
# Create a course
curl -X POST http://localhost:3000/api/courses -H "Content-Type: application/json" -d '{"title":"Next.js Tutorial","slug":"next-js-tutorial","category":"Frontend"}'
# Update a course
curl -X PUT http://localhost:3000/api/courses/1 -H "Content-Type: application/json" -d '{"title":"React JS Complete Guide"}'
# Delete a course
curl -X DELETE http://localhost:3000/api/courses/1
```
REST API Design Best Practices
Use Proper HTTP Methods
| Method | Purpose | Example |
|--------|---------|---------|
| GET | Retrieve data | GET /api/courses |
| POST | Create new resource | POST /api/courses |
| PUT | Update entire resource | PUT /api/courses/1 |
| PATCH | Partial update | PATCH /api/courses/1 |
| DELETE | Remove resource | DELETE /api/courses/1 |
Use Proper Status Codes
| Code | Meaning |
|------|---------|
| 200 | OK - Request succeeded |
| 201 | Created - Resource created |
| 400 | Bad Request - Invalid input |
| 401 | Unauthorized - Not authenticated |
| 404 | Not Found - Resource doesn't exist |
| 500 | Internal Server Error |
Organize Routes Properly
```javascript
// routes/courses.js
const express = require('express')
const router = express.Router()
// GET /api/courses
router.get('/', (req, res) => {
res.json({ success: true, data: [] })
})
// GET /api/courses/:id
router.get('/:id', (req, res) => {
res.json({ success: true, data: {} })
})
// POST /api/courses
router.post('/', (req, res) => {
res.status(201).json({ success: true })
})
module.exports = router
// index.js - use the routes
const courseRoutes = require('./routes/courses')
app.use('/api/courses', courseRoutes)
```
Connecting to MongoDB with Mongoose
Mongoose is an Object Data Modeling (ODM) library that makes working with MongoDB in Node.js straightforward:
```bash
# Install Mongoose
npm install mongoose
```
```javascript
// config/database.js
const mongoose = require('mongoose')
const connectDB = async () => {
try {
const conn = await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/cyberdefence')
console.log(`MongoDB Connected: ${conn.connection.host}`)
} catch (error) {
console.error('MongoDB connection error:', error.message)
process.exit(1)
}
}
module.exports = connectDB
// index.js
const express = require('express')
const mongoose = require('mongoose')
const connectDB = require('./config/database')
const app = express()
const PORT = process.env.PORT || 3000
// Connect to MongoDB
connectDB()
// Middleware
app.use(express.json())
// Routes
app.get('/', (req, res) => {
res.json({ message: 'Node.js API with MongoDB' })
})
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`)
})
```
Defining Mongoose Models
```javascript
// models/Course.js
const mongoose = require('mongoose')
const courseSchema = new mongoose.Schema({
title: {
type: String,
required: [true, 'Course title is required'],
trim: true,
maxlength: [100, 'Title cannot exceed 100 characters']
},
slug: {
type: String,
required: true,
unique: true,
lowercase: true
},
description: {
type: String,
required: [true, 'Description is required'],
maxlength: [500, 'Description cannot exceed 500 characters']
},
category: {
type: String,
enum: ['Frontend', 'Backend', 'Database', 'DevOps'],
default: 'Frontend'
},
price: {
type: Number,
min: 0,
default: 0
},
isPublished: {
type: Boolean,
default: false
},
createdAt: {
type: Date,
default: Date.now
}
}, {
timestamps: true,
toJSON: { virtuals: true },
toObject: { virtuals: true }
})
// Index for search
courseSchema.index({ title: 'text', description: 'text' })
// Pre-save hook to generate slug
courseSchema.pre('save', function(next) {
if (!this.slug) {
this.slug = this.title
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/(^-|-$)/g, '')
}
next()
})
const Course = mongoose.model('Course', courseSchema)
module.exports = Course
```
CRUD Operations with Mongoose
```javascript
// controllers/courseController.js
const Course = require('../models/Course')
// @desc Get all courses
// @route GET /api/courses
exports.getCourses = async (req, res) => {
try {
const courses = await Course.find({ isPublished: true })
.select('-__v')
.sort({ createdAt: -1 })
res.json({
success: true,
count: courses.length,
data: courses
})
} catch (error) {
res.status(500).json({
success: false,
message: 'Server error'
})
}
}
// @desc Get single course
// @route GET /api/courses/:slug
exports.getCourse = async (req, res) => {
try {
const course = await Course.findOne({ slug: req.params.slug })
if (!course) {
return res.status(404).json({
success: false,
message: 'Course not found'
})
}
res.json({
success: true,
data: course
})
} catch (error) {
res.status(500).json({
success: false,
message: 'Server error'
})
}
}
// @desc Create new course
// @route POST /api/courses
exports.createCourse = async (req, res) => {
try {
const { title, slug, description, category, price } = req.body
// Check if course with slug already exists
const existingCourse = await Course.findOne({ slug })
if (existingCourse) {
return res.status(400).json({
success: false,
message: 'A course with this slug already exists'
})
}
const course = await Course.create({
title,
slug,
description,
category,
price,
isPublished: false
})
res.status(201).json({
success: true,
data: course
})
} catch (error) {
// Handle validation errors
if (error.name === 'ValidationError') {
const messages = Object.values(error.errors).map(e => e.message)
return res.status(400).json({
success: false,
message: messages.join(', ')
})
}
res.status(500).json({
success: false,
message: 'Server error'
})
}
}
// @desc Update course
// @route PUT /api/courses/:id
exports.updateCourse = async (req, res) => {
try {
let course = await Course.findById(req.params.id)
if (!course) {
return res.status(404).json({
success: false,
message: 'Course not found'
})
}
course = await Course.findByIdAndUpdate(
req.params.id,
req.body,
{
new: true,
runValidators: true
}
)
res.json({
success: true,
data: course
})
} catch (error) {
res.status(500).json({
success: false,
message: 'Server error'
})
}
}
// @desc Delete course
// @route DELETE /api/courses/:id
exports.deleteCourse = async (req, res) => {
try {
const course = await Course.findById(req.params.id)
if (!course) {
return res.status(404).json({
success: false,
message: 'Course not found'
})
}
await course.deleteOne()
res.json({
success: true,
message: 'Course deleted successfully'
})
} catch (error) {
res.status(500).json({
success: false,
message: 'Server error'
})
}
}
```
Authentication with JWT in Node.js
```bash
# Install JWT and bcrypt for password hashing
npm install jsonwebtoken bcryptjs
```
```javascript
// middleware/auth.js
const jwt = require('jsonwebtoken')
const auth = async (req, res, next) => {
try {
// Get token from header
const token = req.header('Authorization')?.replace('Bearer ', '')
if (!token) {
return res.status(401).json({
success: false,
message: 'Access denied. No token provided.'
})
}
// Verify token
const decoded = jwt.verify(token, process.env.JWT_SECRET)
// Add user to request
req.user = decoded
next()
} catch (error) {
res.status(401).json({
success: false,
message: 'Invalid token'
})
}
}
module.exports = auth
// auth controller
const User = require('../models/User')
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
exports.register = async (req, res) => {
try {
const { name, email, password } = req.body
// Check if user exists
let user = await User.findOne({ email })
if (user) {
return res.status(400).json({
success: false,
message: 'User already exists with this email'
})
}
// Hash password
const salt = await bcrypt.genSalt(10)
const hashedPassword = await bcrypt.hash(password, salt)
// Create user
user = await User.create({
name,
email,
password: hashedPassword
})
// Generate JWT
const token = jwt.sign(
{ id: user._id },
process.env.JWT_SECRET,
{ expiresIn: '7d' }
)
res.status(201).json({
success: true,
token,
user: {
id: user._id,
name: user.name,
email: user.email
}
})
} catch (error) {
res.status(500).json({
success: false,
message: 'Server error'
})
}
}
exports.login = async (req, res) => {
try {
const { email, password } = req.body
// Find user
const user = await User.findOne({ email })
if (!user) {
return res.status(400).json({
success: false,
message: 'Invalid credentials'
})
}
// Check password
const isMatch = await bcrypt.compare(password, user.password)
if (!isMatch) {
return res.status(400).json({
success: false,
message: 'Invalid credentials'
})
}
// Generate JWT
const token = jwt.sign(
{ id: user._id },
process.env.JWT_SECRET,
{ expiresIn: '7d' }
)
res.json({
success: true,
token,
user: {
id: user._id,
name: user.name,
email: user.email
}
})
} catch (error) {
res.status(500).json({
success: false,
message: 'Server error'
})
}
}
```
Error Handling Best Practices
```javascript
// Global error handler
const errorHandler = (err, req, res, next) => {
console.error('Error:', err.stack)
// Mongoose bad ObjectId
if (err.name === 'CastError') {
return res.status(400).json({
success: false,
message: 'Resource not found'
})
}
// Mongoose duplicate key
if (err.code === 11000) {
return res.status(400).json({
success: false,
message: 'Duplicate field value entered'
})
}
// Mongoose validation error
if (err.name === 'ValidationError') {
const messages = Object.values(err.errors).map(e => e.message)
return res.status(400).json({
success: false,
message: messages.join(', ')
})
}
// JWT errors
if (err.name === 'JsonWebTokenError') {
return res.status(401).json({
success: false,
message: 'Invalid token'
})
}
// Default server error
res.status(500).json({
success: false,
message: 'Server error'
})
}
app.use(errorHandler)
```
Next Steps After This Node.js Tutorial
After completing this Node.js tutorial:
- Connect your API to a frontend React application
- Learn deployment with Railway, Render, or Vercel
- Explore authentication libraries like Passport.js
- Practice by building a blog API with categories and comments
For structured backend development training in India, the full stack developer course at Cyber Defence in Hisar, Haryana covers Node.js, Express, and MongoDB as part of its comprehensive MERN stack curriculum.
FAQ: Node.js Tutorial for Backend Development
How long does it take to learn Node.js?
With 2-3 hours of daily practice, you can learn Node.js basics in 2-4 weeks. Building job-ready proficiency for backend development takes 2-4 months of focused learning and project building.
Is Node.js a backend framework?
Node.js is a runtime environment that executes JavaScript on the server. Express.js is the actual backend framework commonly used with Node.js. Together, they form the back-end portion of the MERN stack.
Can I use Node.js for frontend development?
Node.js is primarily used for backend development, but it also powers front-end build tools (Webpack, Vite), package managers (npm, yarn), and modern frameworks (Next.js). So yes, Node.js is indirectly used in front-end development as well.
What is Express.js?
Express.js is a minimal, fast, and flexible Node.js web application framework. It provides features for web and mobile applications, routing, middleware, and API development. Express simplifies Node.js development significantly.
What is the salary of a Node.js developer in India?
Entry-level Node.js developers earn Rs 4 to 8 LPA. Mid-level developers with Express and database skills earn Rs 8 to 16 LPA. Senior Node.js engineers earn Rs 18 to 40 LPA.
Do I need to know JavaScript before learning Node.js?
Yes, solid JavaScript knowledge is essential before learning Node.js. Focus on ES6 features (arrow functions, promises, async/await, destructuring), array methods (map, filter, reduce), and object manipulation. This JavaScript tutorial for beginners covers the prerequisites.

