A high-performance RESTful API built with Fastify and Node.js
A robust backend RESTful API designed for secure user authentication and video thumbnail management. Built with Fastify for high performance, MongoDB for flexible data storage, and JWT for secure authentication.
Features β’ Quick Start β’ API Documentation β’ Deployment
- Features
- Tech Stack
- Prerequisites
- Quick Start
- Project Structure
- API Documentation
- Environment Variables
- Testing
- Deployment
- Troubleshooting
- Contributing
- License
- User Registration & Login - Secure user account creation and authentication
- JWT Token-based Auth - Stateless authentication using JSON Web Tokens
- Password Reset Flow - Email-based password recovery with time-limited tokens
- Protected Routes - Middleware-based route protection for sensitive endpoints
- Password Hashing - Bcrypt password encryption for secure storage
- Image Upload - Multipart form data support for file uploads
- CRUD Operations - Full Create, Read, Update, Delete operations for thumbnails
- User-scoped Resources - Each user can only access their own thumbnails
- Bulk Operations - Delete all thumbnails for a user in one request
- File System Storage - Efficient local storage with organized directory structure
- RESTful Architecture - Clean, predictable API design
- Error Handling - Comprehensive error logging and graceful failure handling
- CORS Enabled - Cross-Origin Resource Sharing configured for frontend integration
- Environment-based Config - Flexible deployment with environment variables
- Database Health Check - Utility endpoint to monitor MongoDB connection status
| Technology | Purpose |
|---|---|
| Node.js | JavaScript runtime environment |
| Fastify | High-performance web framework |
| MongoDB | NoSQL database for flexible data storage |
| Mongoose | Elegant MongoDB object modeling |
| JWT | Secure token-based authentication |
| Bcrypt.js | Password hashing algorithm |
Before you begin, ensure you have the following installed:
- Node.js (v14 or higher) - Download
- npm or yarn - Comes with Node.js
- MongoDB (v4 or higher) - Download or use MongoDB Atlas
- Git - Download
git clone https://github.com/dev0jha/FastifyBackend.git
cd FastifyBackendnpm installCreate a .env file in the root directory:
cp .env.example .envEdit the .env file with your configuration:
PORT=3000
MONGODB_URI=mongodb://localhost:27017/fastifybackend
JWT_TOKEN=your_super_secret_jwt_key_change_this_in_production
JWT_SECRET=your_super_secret_jwt_key_change_this_in_production
β οΈ Security Note: Never commit your.envfile to version control. Use strong, unique secrets in production.
mkdir -p uploads/thumbnailsDevelopment Mode:
npm startWith nodemon (auto-restart on changes):
npm install -g nodemon
nodemon server.jsThe server will start at http://localhost:3000
Test the database connection:
curl http://localhost:3000/test-dbExpected response:
{"database":"connected"}FastifyBackend/
βββ π controllers/ # Request handlers and business logic
β βββ authController.js # Authentication operations
β βββ thumbnailController.js # Thumbnail CRUD operations
β
βββ π models/ # Mongoose schemas and models
β βββ user.js # User model definition
β βββ thumbnail.js # Thumbnail model definition
β
βββ π plugins/ # Fastify plugins
β βββ jwt.js # JWT authentication plugin
β βββ mongodb.js # MongoDB connection plugin
β
βββ π routes/ # API route definitions
β βββ auth.js # Authentication routes
β βββ thumbnail.js # Thumbnail routes
β
βββ π uploads/ # File storage
β βββ thumbnails/ # Uploaded thumbnail images
β
βββ π server.js # Application entry point
βββ π package.json # Project dependencies
βββ π .env.example # Environment variables template
βββ π README.md # Project documentation
http://localhost:3000
POST /api/auth/register
Content-Type: application/jsonRequest Body:
{
"name": "John Doe",
"email": "john@example.com",
"password": "SecurePassword123!",
"country": "United States"
}Response: 201 Created
{
"message": "user registered successfully"
}POST /api/auth/login
Content-Type: application/jsonRequest Body:
{
"email": "john@example.com",
"password": "SecurePassword123!"
}Response: 200 OK
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}POST /api/auth/forgot-password
Content-Type: application/jsonRequest Body:
{
"email": "john@example.com"
}Response: 200 OK
{
"resetUrl": "http://localhost:3000/api/auth/reset-password/abc123..."
}POST /api/auth/reset-password/:token
Content-Type: application/jsonRequest Body:
{
"newPassword": "NewSecurePassword456!"
}Response: 200 OK
{
"message": "password reset successful"
}POST /api/auth/logout
Authorization: Bearer <JWT_TOKEN>Response: 200 OK
{
"message": "User logged out"
}π All thumbnail endpoints require JWT authentication via
Authorization: Bearer <token>header
POST /api/thumbnail
Authorization: Bearer <JWT_TOKEN>
Content-Type: multipart/form-dataForm Data:
file: Image file (required)videoName: Name of the video (required)version: Version number (required)paid: Boolean - true/false (required)
Response: 201 Created
{
"_id": "507f1f77bcf86cd799439011",
"user": "507f191e810c19729de860ea",
"videoName": "Introduction Tutorial",
"version": "1.0",
"image": "/uploads/thumbnails/1644567890123-thumbnail.jpg",
"paid": false
}GET /api/thumbnail
Authorization: Bearer <JWT_TOKEN>Response: 200 OK
[
{
"_id": "507f1f77bcf86cd799439011",
"user": "507f191e810c19729de860ea",
"videoName": "Introduction Tutorial",
"version": "1.0",
"image": "/uploads/thumbnails/1644567890123-thumbnail.jpg",
"paid": false
}
]GET /api/thumbnail/:id
Authorization: Bearer <JWT_TOKEN>Response: 200 OK
{
"_id": "507f1f77bcf86cd799439011",
"user": "507f191e810c19729de860ea",
"videoName": "Introduction Tutorial",
"version": "1.0",
"image": "/uploads/thumbnails/1644567890123-thumbnail.jpg",
"paid": false
}PUT /api/thumbnail/:id
Authorization: Bearer <JWT_TOKEN>
Content-Type: application/jsonRequest Body:
{
"videoName": "Updated Tutorial Name",
"version": "2.0",
"paid": true
}Response: 200 OK
{
"_id": "507f1f77bcf86cd799439011",
"user": "507f191e810c19729de860ea",
"videoName": "Updated Tutorial Name",
"version": "2.0",
"image": "/uploads/thumbnails/1644567890123-thumbnail.jpg",
"paid": true
}DELETE /api/thumbnail/:id
Authorization: Bearer <JWT_TOKEN>Response: 200 OK
{
"message": "Thumbnail deleted"
}DELETE /api/thumbnail
Authorization: Bearer <JWT_TOKEN>Response: 200 OK
{
"message": "All thumbnails deleted"
}GET /test-dbResponse: 200 OK
{
"database": "connected"
}Possible states: connected, connecting, disconnected, disconnecting
GET /Response: 200 OK
{
"hello": "world"
}Create a .env file in the root directory with the following variables:
| Variable | Description | Required | Example |
|---|---|---|---|
PORT |
Server port number | Yes | 3000 |
MONGODB_URI |
MongoDB connection string | Yes | mongodb://localhost:27017/fastifybackend |
JWT_TOKEN |
Secret key for JWT signing | Yes | your_super_secret_key_here |
JWT_SECRET |
Alternative JWT secret (for compatibility) | Yes | your_super_secret_key_here |
# Server Configuration
PORT=3000
# Database Configuration
MONGODB_URI=mongodb://localhost:27017/fastifybackend
# For MongoDB Atlas:
# MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/dbname?retryWrites=true&w=majority
# JWT Configuration
JWT_TOKEN=change_this_to_a_secure_random_string_in_production
JWT_SECRET=change_this_to_a_secure_random_string_in_productionπ‘ Tip: Generate secure secrets using:
node -e "console.log(require('crypto').randomBytes(64).toString('hex'))"
Register a user:
curl -X POST http://localhost:3000/api/auth/register \
-H "Content-Type: application/json" \
-d '{"name":"Test User","email":"test@example.com","password":"Test123!","country":"USA"}'Login:
curl -X POST http://localhost:3000/api/auth/login \
-H "Content-Type: application/json" \
-d '{"email":"test@example.com","password":"Test123!"}'Upload thumbnail (replace TOKEN with actual JWT):
curl -X POST http://localhost:3000/api/thumbnail \
-H "Authorization: Bearer YOUR_JWT_TOKEN" \
-F "file=@/path/to/image.jpg" \
-F "videoName=Test Video" \
-F "version=1.0" \
-F "paid=false"- Import the API endpoints into Postman
- Create an environment with
baseUrl=http://localhost:3000 - Use the login endpoint to get a JWT token
- Set the token in Authorization header for protected routes
-
Install the Heroku CLI
-
Login to Heroku:
heroku login
-
Create a new Heroku app:
heroku create your-app-name
-
Set environment variables:
heroku config:set MONGODB_URI=your_mongodb_uri heroku config:set JWT_TOKEN=your_jwt_secret heroku config:set JWT_SECRET=your_jwt_secret
-
Deploy:
git push heroku main
-
Install Railway CLI:
npm i -g @railway/cli
-
Initialize and deploy:
railway login railway init railway up
-
Add environment variables in Railway dashboard
Create a Dockerfile:
FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]Build and run:
docker build -t fastify-backend .
docker run -p 3000:3000 --env-file .env fastify-backendProblem: MONGODB connected ! doesn't appear in logs
Solutions:
- Verify MongoDB is running:
mongod --version - Check connection string in
.env - Ensure MongoDB service is started
- For MongoDB Atlas, check network access settings and whitelist your IP
Problem: 401 Unauthorized on protected routes
Solutions:
- Ensure you're sending the token in the
Authorizationheader - Format:
Authorization: Bearer <your-token> - Verify the token hasn't expired (default: no expiration in this setup)
- Check
JWT_SECRETmatches between login and authentication
Problem: Thumbnail upload fails
Solutions:
- Ensure
uploads/thumbnails/directory exists - Check file permissions on the uploads directory
- Verify
Content-Type: multipart/form-datais set - Check file size limits (if any)
Problem: EADDRINUSE: address already in use :::3000
Solutions:
- Kill the process using port 3000:
# On Linux/Mac lsof -ti:3000 | xargs kill -9 # On Windows netstat -ano | findstr :3000 taskkill /PID <PID> /F
- Or use a different port in
.env
Contributions are welcome! Here's how you can help:
- Fork the repository
- Create a feature branch
git checkout -b feature/AmazingFeature
- Commit your changes
git commit -m 'Add some AmazingFeature' - Push to the branch
git push origin feature/AmazingFeature
- Open a Pull Request
- Follow existing code style and conventions
- Write clear commit messages
- Add comments for complex logic
- Update documentation for new features
- Test your changes thoroughly
This project is licensed under the MIT License - see the LICENSE file for details.
dev0jha
- GitHub: @dev0jha
- Repository: FastifyBackend
If you find this project helpful, please consider giving it a βοΈ
Made with β€οΈ by dev0jha