Node.js Framework Selection
When choosing a Node.js framework, consider:
- Koa2 - Minimalist framework with middleware support
- Express - Most popular with extensive middleware ecosystem
- Egg.js - Enterprise framework built on Koa
- NestJS - TypeScript framework with Angular-like architecture
// Koa2 basic server example
const Koa = require('koa');
const app = new Koa();
app.use(async ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
Database Technologies
Relational Database (MySQL)
Using Sequelize ORM:
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize('database', 'user', 'password', {
host: 'localhost',
dialect: 'mysql'
});
Document Data base (MongoDB)
Using Mongoose ODM:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
const Schema = mongoose.Schema;
const blogSchema = new Schema({
title: String,
content: String
});
In-Memory Database (Redis)
const redis = require('redis');
const client = redis.createClient();
client.set('key', 'value', redis.print);
client.get('key', (err, reply) => {
console.log(reply);
});
Authentication Strtaegies
JWT Implementation
const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 123 }, 'secret', { expiresIn: '1h' });
// Verify middleware
const verifyToken = (req, res, next) => {
const token = req.headers['authorization'];
if (!token) return res.status(403).send('Token required');
jwt.verify(token, 'secret', (err, decoded) => {
if (err) return res.status(500).send('Invalid token');
req.userId = decoded.userId;
next();
});
};
Testing Strategeis
Unit Testing with Jest
// math.js
function sum(a, b) {
return a + b;
}
module.exports = sum;
// math.test.js
const sum = require('./math');
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3);
});
API Testing with Supertest
const request = require('supertest');
const app = require('../app');
describe('GET /users', () => {
it('responds with json', async () => {
const response = await request(app)
.get('/users')
.expect('Content-Type', /json/)
.expect(200);
});
});
Deployment Configuration
PM2 Process Manager
module.exports = {
apps: [{
name: 'api-server',
script: './server.js',
instances: 'max',
exec_mode: 'cluster',
env: {
NODE_ENV: 'production'
}
}]
};
Nginx Reverse Proxy
server {
listen 80;
server_name api.example.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
CI/CD with GitHub Actions
name: Node.js CI
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js
uses: actions/setup-node@v1
with:
node-version: '14.x'
- run: npm install
- run: npm test
Docker Configuration
# Dockerfile
FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
Docker Compose
version: '3'
services:
web:
build: .
ports:
- "3000:3000"
redis:
image: "redis:alpine"