Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

6 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ FastifyBackend

A high-performance RESTful API built with Fastify and Node.js

Node.js Fastify MongoDB JWT License: MIT

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


πŸ“‹ Table of Contents


✨ Features

πŸ” Authentication & Security

  • 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

πŸ–ΌοΈ Thumbnail Management

  • 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

πŸ› οΈ Developer Experience

  • 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

πŸ”§ Tech Stack

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

πŸ“¦ Prerequisites

Before you begin, ensure you have the following installed:


πŸš€ Quick Start

1️⃣ Clone the Repository

git clone https://github.com/dev0jha/FastifyBackend.git
cd FastifyBackend

2️⃣ Install Dependencies

npm install

3️⃣ Configure Environment Variables

Create a .env file in the root directory:

cp .env.example .env

Edit 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 .env file to version control. Use strong, unique secrets in production.

4️⃣ Create Upload Directory

mkdir -p uploads/thumbnails

5️⃣ Start the Server

Development Mode:

npm start

With nodemon (auto-restart on changes):

npm install -g nodemon
nodemon server.js

The server will start at http://localhost:3000

6️⃣ Verify Installation

Test the database connection:

curl http://localhost:3000/test-db

Expected response:

{"database":"connected"}

πŸ“ Project Structure

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

πŸ“š API Documentation

Base URL

http://localhost:3000

πŸ”‘ Authentication Endpoints

Register a New User

POST /api/auth/register
Content-Type: application/json

Request Body:

{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "SecurePassword123!",
  "country": "United States"
}

Response: 201 Created

{
  "message": "user registered successfully"
}

Login

POST /api/auth/login
Content-Type: application/json

Request Body:

{
  "email": "john@example.com",
  "password": "SecurePassword123!"
}

Response: 200 OK

{
  "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}

Forgot Password

POST /api/auth/forgot-password
Content-Type: application/json

Request Body:

{
  "email": "john@example.com"
}

Response: 200 OK

{
  "resetUrl": "http://localhost:3000/api/auth/reset-password/abc123..."
}

Reset Password

POST /api/auth/reset-password/:token
Content-Type: application/json

Request Body:

{
  "newPassword": "NewSecurePassword456!"
}

Response: 200 OK

{
  "message": "password reset successful"
}

Logout

POST /api/auth/logout
Authorization: Bearer <JWT_TOKEN>

Response: 200 OK

{
  "message": "User logged out"
}

πŸ–ΌοΈ Thumbnail Endpoints

πŸ”’ All thumbnail endpoints require JWT authentication via Authorization: Bearer <token> header

Upload Thumbnail

POST /api/thumbnail
Authorization: Bearer <JWT_TOKEN>
Content-Type: multipart/form-data

Form 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 All Thumbnails (Current User)

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 Single Thumbnail

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
}

Update Thumbnail

PUT /api/thumbnail/:id
Authorization: Bearer <JWT_TOKEN>
Content-Type: application/json

Request 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 Single Thumbnail

DELETE /api/thumbnail/:id
Authorization: Bearer <JWT_TOKEN>

Response: 200 OK

{
  "message": "Thumbnail deleted"
}

Delete All Thumbnails (Current User)

DELETE /api/thumbnail
Authorization: Bearer <JWT_TOKEN>

Response: 200 OK

{
  "message": "All thumbnails deleted"
}

πŸ› οΈ Utility Endpoints

Test Database Connection

GET /test-db

Response: 200 OK

{
  "database": "connected"
}

Possible states: connected, connecting, disconnected, disconnecting


Health Check

GET /

Response: 200 OK

{
  "hello": "world"
}

πŸ” Environment Variables

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

Example .env File

# 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'))"

πŸ§ͺ Testing

Manual Testing with cURL

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"

Testing with Postman

  1. Import the API endpoints into Postman
  2. Create an environment with baseUrl = http://localhost:3000
  3. Use the login endpoint to get a JWT token
  4. Set the token in Authorization header for protected routes

πŸš€ Deployment

Deploy to Heroku

  1. Install the Heroku CLI

  2. Login to Heroku:

    heroku login
  3. Create a new Heroku app:

    heroku create your-app-name
  4. 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
  5. Deploy:

    git push heroku main

Deploy to Railway

  1. Install Railway CLI:

    npm i -g @railway/cli
  2. Initialize and deploy:

    railway login
    railway init
    railway up
  3. Add environment variables in Railway dashboard

Deploy with Docker

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-backend

πŸ› Troubleshooting

Common Issues

MongoDB Connection Failed

Problem: 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

JWT Authentication Errors

Problem: 401 Unauthorized on protected routes

Solutions:

  • Ensure you're sending the token in the Authorization header
  • Format: Authorization: Bearer <your-token>
  • Verify the token hasn't expired (default: no expiration in this setup)
  • Check JWT_SECRET matches between login and authentication

File Upload Errors

Problem: Thumbnail upload fails

Solutions:

  • Ensure uploads/thumbnails/ directory exists
  • Check file permissions on the uploads directory
  • Verify Content-Type: multipart/form-data is set
  • Check file size limits (if any)

Port Already in Use

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

🀝 Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create a feature branch
    git checkout -b feature/AmazingFeature
  3. Commit your changes
    git commit -m 'Add some AmazingFeature'
  4. Push to the branch
    git push origin feature/AmazingFeature
  5. Open a Pull Request

Development Guidelines

  • Follow existing code style and conventions
  • Write clear commit messages
  • Add comments for complex logic
  • Update documentation for new features
  • Test your changes thoroughly

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ‘¨β€πŸ’» Author

dev0jha


πŸ™ Acknowledgments

  • Fastify - Fast and low overhead web framework
  • MongoDB - Database platform
  • JWT - JSON Web Tokens

If you find this project helpful, please consider giving it a ⭐️

Made with ❀️ by dev0jha

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages