Deep ExpressJS Notes Cosmas
Deep ExpressJS Notes Cosmas
js
Express.js is a minimalist web framework for Node.js.
It simplifies building robust APIs and web apps.
Key features:
- Middleware support
- Routing system
- Integration with templating engines
- Error handling
- Support for RESTful APIs
- Can be used with any database
4. Middleware
Middleware functions have access to req, res, next.
Types:
- Application-level
- Router-level
- Error-handling
- Built-in (express.json, express.static)
- Third-party (morgan, cors)
Example:
app.use(express.json()); // Parse JSON bodies
app.use((req, res, next) => { console.log(req.url); next(); });
5. Routing in Express
Defines endpoints for HTTP methods.
app.get(path, handler)
app.post(path, handler)
Supports parameters, queries, chaining, regex, etc.
Example:
app.get('/user/:id', (req, res) => res.send(req.params.id));
6. Express Router
Use express.Router() to modularize routes.
Example:
const router = express.Router();
router.get('/', ...);
module.exports = router;
app.use('/api/users', require('./routes/users'));
8. Templating Engines
Render HTML dynamically using EJS, Pug, Handlebars.
Set up EJS:
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
res.render('template', { title: 'My App' });
9. Static Files
To serve images, CSS, JS:
app.use(express.static('public'));
Access via http://localhost:3000/style.css if in /public/style.css
10. Forms & Validation
Use express.urlencoded() to parse form data:
app.use(express.urlencoded({ extended: true }));
Validate data manually or use libraries (e.g. express-validator)
15. Authentication
- Sessions with express-session
- JWT with jsonwebtoken
Steps:
1. Login user -> generate JWT -> send token
2. Protect routes by verifying token in middleware
3. Logout by destroying token on client
19. Deployment
- Upload project to GitHub
- Use services like Render, Railway, Vercel, or VPS
- Use PM2 to keep app running in background
- Set environment variables on the platform