Bangu Blogs Server is a robust backend application built for managing blogs with user authentication, role-based access control, and comprehensive API functionalities. It supports both Admin and User roles with tailored permissions and features.
- User Authentication & Authorization: Secure login with role-based access control (Admin, User).
- Role Management: Admins can block users and manage all blogs, while users can manage their own content.
- JWT-Based Security: Access and refresh tokens ensure secure session management.
- Middleware Protection: Role-based access enforced through middleware (
authorizeUser
). - Blog Management: Full CRUD operations for blogs, with ownership validation.
- Search, Sort & Filter: Efficient querying powered by a reusable
QueryBuilder
class, designed to support future module expansions. - Password Encryption: User passwords are securely hashed using bcrypt.
- Data Validation: Input validated with Zod schemas to ensure data integrity.
- Scalable Architecture: Modular and well-structured backend code for maintainability.
- TypeScript β Typed JavaScript for better scalability and maintainability.
- Node.js β JavaScript runtime environment.
- Express.js β Fast, unopinionated web framework for Node.js.
- Mongoose β Elegant MongoDB object modeling for Node.js.
- bcrypt β Library for hashing passwords.
- jsonwebtoken β Implementation of JSON Web Tokens for authentication.
- cookie-parser β Middleware to parse cookies in requests.
- zod β TypeScript-first schema validation library.
- cors β Middleware for enabling CORS in Express.
- dotenv β Loads environment variables from a
.env
file.
- eslint β Linter for identifying problematic patterns in code.
- prettier β Code formatter for consistent styling.
- chalk β Terminal string styling for improved CLI output.
- progress-estimator β Estimate and display task progress.
- execa β Better
child_process
management. - rimraf β Cross-platform tool for recursive file deletion.
- globby β Advanced globbing library for file matching (in
build.mjs
). - nodemon β Utility for automatically restarting the server during development.
- ts-node β Run TypeScript in development directly without manual compilation.
Node.js
(Preferredv22+
)pnpm
package manager- If you prefer
npm
oryarn
overpnpm
, deletepnpm-lock.yaml
file and follow the steps below.
-
Clone the repository:
git clone https://github.com/nazmul-nhb/bangu-blogs-server.git cd bangu-blogs-server
-
Install dependencies:
pnpm install
for
npm
:npm install
for
yarn
:yarn install
-
Set up environment variables: Create a
.env
file in the root directory with the following fields:NODE_ENV=development PORT=4242 or any port number SALT_ROUNDS=<number> MONGO_URI=your_mongo_db_uri JWT_ACCESS_SECRET=secret_string_for_access_token JWT_ACCESS_EXPIRES_IN=expiry_time (1h, 1d etc.) JWT_REFRESH_SECRET=secret_string_for_refresh_token JWT_REFRESH_EXPIRES_IN=expiry_time (1h, 1d etc.)
-
Start the development server:
pnpm dev
for
npm
:npm run dev
for
yarn
:yarn run dev
-
Access the API at:
http://localhost:4242
-
Endpoint:
POST /api/auth/register
-
Description: Register a new user.
-
Request Body:
{ "name": "John Doe", "email": "john@example.com", "password": "123456" }
-
Response:
{ "success": true, "message": "User registered successfully!", "statusCode": 201, "data": { "_id": "string", "name": "string", "email": "string" } }
-
Endpoint:
POST /api/auth/login
-
Description: Authenticate a user and retrieve a JWT token.
-
Request Body:
{ "email": "john@example.com", "password": "123456" }
-
Response:
{ "success": true, "message": "Login successful!", "statusCode": 200, "data": { "token": "string" } }
-
Endpoint:
POST /api/blogs
-
Description: Create a new blog (User only).
-
Request Header:
Authorization: Bearer <token>
-
Request Body:
{ "title": "My First Blog", "content": "This is my blog content." }
-
Response:
{ "success": true, "message": "Blog created successfully!", "statusCode": 201, "data": { "_id": "string", "title": "My First Blog", "content": "This is my blog content.", "author": { "_id": "author id", "name": "author name", "email": "author email" } } }
-
Endpoint:
PATCH /api/blogs/:id
-
Description: Update an existing blog (User only).
-
Request Header:
Authorization: Bearer <token>
-
Request Body:
{ "title": "Updated Blog Title", "content": "Updated content." }
-
Response
{ "success": true, "message": "Blog updated successfully", "statusCode": 200, "data": { "_id": "string", "title": "string", "content": "string", "author": { "_id": "author id", "name": "author name", "email": "author email" } } }
-
Endpoint:
DELETE /api/blogs/:id
-
Description: Delete a blog (User).
-
Request Header:
Authorization: Bearer <token>
-
Response
{ "success": true, "message": "Blog deleted successfully!", "statusCode": 200 }
-
Endpoint:
PATCH /api/admin/users/:userId/block
-
Description: Allows an admin to block a user by updating the
isBlocked
property totrue
. -
Request Header:
Authorization: Bearer <admin_token>
-
Response
{ "success": true, "message":"User blocked successfully!", "statusCode": 200 }
-
Endpoint:
DELETE /api/admin/blogs/:id
-
Description: Delete any blog.
-
Request Header:
Authorization: Bearer <admin_token>
-
Response
{ "success": true, "message": "Blog deleted successfully!", "statusCode": 200 }
- Endpoint:
GET /api/blogs
- Query Parameters:
search
: Search blogs bytitle
orcontent
(e.g.,search=productivity
).sortBy
: Sort blogs by specific fields such ascreatedAt
ortitle
(e.g.,sortBy=title
).sortOrder
: Defines the sorting order. Accepts valuesasc
(ascending) ordesc
(descending). (e.g.,sortOrder=desc
).filter
: Filter blogs by author ID (e.g.,author=authorId
).
Example Request URL:
/api/blogs?search=productivity&sortBy=title&sortOrder=desc&filter=676652d0b7adefd7d645a727
In this example:
search=technology
: Filters blogs containing the term "technology" in the title or content.sortBy=title
: Sorts the blogs by thetitle
field.sortOrder=desc
: Sorts in descending order (newest blogs first).filter=676652d0b7adefd7d645a727
: Filters blogs authored by the user with the givenauthorId
.
Response:
{
"success": true,
"message": "Blogs fetched successfully!",
"statusCode": 200,
"data": [
{
"_id": "string",
"title": "string",
"content": "string",
"author": {
"_id": "author id",
"name": "author name",
"email": "author email"
}
},
{...}
]
}
All error responses follow a consistent structure:
{
"success": false,
"message": "Error message",
"statusCode": 400,
"error": { "details": [
{
"name": "Error name",
"path": "where error occurred if traced",
"message": "Error message"
},
{...}
]
},
"stack": "Error stack trace if available"
}
Implemented custom progress indicators using progress-estimator
, globby
and chalk
for key development tasks to improve visibility and clarity during long-running processes:
- Build:
pnpm build
β Displays progress while building the project. - Lint:
pnpm lint
β Provides real-time progress feedback during linting. - Fix:
pnpm fix
β Tracks progress while auto-fixing linting issues. - Deploy:
pnpm run deploy
β Builds the project and deploys it to Vercel with production settings, displaying progress for both stages.
- Email:
admin@bangu.com
- Password:
123456