Express.js: Framework Node.js yang Bikin Backend Development Jadi Gampang
Mau bikin backend API tapi bingung mulai dari mana? Express.js adalah jawabannya!
Framework Node.js yang satu ini udah jadi pilihan utama developer di seluruh dunia. Ringan, fleksibel, dan punya ecosystem yang kaya banget.
Kenapa Harus Express.js?
- ⚡ Fast & Lightweight – Minimal overhead, performa tinggi
- 🔧 Flexible – Bisa disesuaikan dengan kebutuhan project
- 📦 Rich Ecosystem – Ribuan middleware siap pakai
- 🚀 Easy to Learn – Syntax yang simple dan intuitif
Setup Project Express.js
1️⃣ Inisialisasi Project
mkdir my-express-app
cd my-express-app
npm init -y
npm install express
2️⃣ Basic Server Setup
// app.js
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware untuk parsing JSON
app.use(express.json());
// Route dasar
app.get('/', (req, res) => {
res.json({ message: 'Hello World dari Express.js!' });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Routing di Express.js
HTTP Methods
// GET - Ambil data
app.get('/users', (req, res) => {
res.json({ users: ['Alice', 'Bob', 'Charlie'] });
});
// POST - Kirim data baru
app.post('/users', (req, res) => {
const { name } = req.body;
res.json({ message: `User ${name} berhasil ditambahkan!` });
});
// PUT - Update data
app.put('/users/:id', (req, res) => {
const { id } = req.params;
res.json({ message: `User dengan ID ${id} berhasil diupdate` });
});
// DELETE - Hapus data
app.delete('/users/:id', (req, res) => {
const { id } = req.params;
res.json({ message: `User dengan ID ${id} berhasil dihapus` });
});
Route Parameters & Query
// Route parameter
app.get('/users/:id', (req, res) => {
const { id } = req.params;
res.json({ userId: id });
});
// Query parameters
app.get('/search', (req, res) => {
const { q, limit = 10 } = req.query;
res.json({
query: q,
limit: parseInt(limit),
results: [],
});
});
Middleware yang Wajib Tahu
1️⃣ Built-in Middleware
app.use(express.json());
// Parsing URL-encoded data
app.use(express.urlencoded({ extended: true }));
// Serve static files
app.use(express.static('public'));
2️⃣ Custom Middleware
// Logging middleware
const logger = (req, res, next) => {
console.log(`${req.method} ${req.path} - ${new Date().toISOString()}`);
next();
};
app.use(logger);
// Auth middleware
const requireAuth = (req, res, next) => {
const token = req.headers.authorization;
if (!token) {
return res.status(401).json({ error: 'Token required' });
}
// Verify token logic here...
next();
};
app.get('/protected', requireAuth, (req, res) => {
res.json({ message: 'Ini route yang protected!' });
});
Error Handling
// Error handling middleware
const errorHandler = (err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500).json({
error: {
message: err.message || 'Something went wrong!',
...(process.env.NODE_ENV === 'development' && { stack: err.stack }),
},
});
};
// 404 handler
app.use('*', (req, res) => {
res.status(404).json({ error: 'Route not found' });
});
// Gunakan error handler di akhir
app.use(errorHandler);
Penutup
Aksesibilitas itu bukan cuma soal compliance. Ini tentang membuat web yang bisa dinikmati semua orang tanpa hambatan.
Connect With Me:
Instagram: @novinbukannopin
LinkedIn: novin
Tiktok: @lovinnnnnnnn
X/Twitter: @novinbukannopin
GitHub: @novinbukannopin