Documentación del backend: instalación, configuración, endpoints, ejemplos y dependencias.
Introduction
This project is a robust backend API designed for a social media platform. It provides essential features such as user registration and authentication, the ability to create and manage posts, and a system to follow or unfollow other users to build social connections.
While this API does not support real-time interactions like live messaging or notifications, it offers a solid foundation for managing user data and social content, which can be extended with additional services if needed.
This project is a simple backend API for a social media platform. It allows users to register, log in, create posts, and follow or unfollow other users to build social connections.
Although it doesn’t include real-time features like live messaging or notifications, it provides a basic structure to manage user data and social interactions, which can be expanded with more advanced functionalities if desired.
The project emphasizes learning and practicing backend development concepts, including authentication, data management, and RESTful API design.
This project is primarily intended as a personal practice tool for backend development, but it can also be helpful for others who want to learn or build upon it.
Prerequisites
Before installing the project, ensure you have the following tools installed:
- Node.js (v18 or newer recommended)
- npm (comes bundled with Node.js)
- MongoDB (running locally or via an external service)
- Git (to clone the repository)
Installation
Clone the repository and run npm install to install dependencies. Then use npm start to run the server.
Installation Steps
Clone the repository:
git clone https://github.com/migusmp/social-media-api.gitNavigate to the project directory:
cd social-media-apiInstall dependencies:
npm installStart the server:
npm start
🔧 Required Configuration Before Starting the Server
Before running npm start, make sure to create a .env file at the root of the project and define the following environment variables:
DATABASE_URL: The connection string to your database. This allows your application to connect and work with MongoDB database.SECRET_PAYLOAD_KEY: A secret string used to encrypt and verify authentication data such as JWTs. This key should be unique and secure.
Example of a .env file:
DATABASE_URL=mongodb://user:password@localhost:27017/database_name
SECRET_PAYLOAD_KEY=your_super_secret_jwt_key🛠️ How to create a MongoDB database if you don’t have one
If you don't have a MongoDB database yet, you can create one easily using Docker. Choose your operating system:
To run MongoDB using Docker on Linux, you can use the following command:
docker run -d --name mongodb -p 27017:27017 -v mongodbdata:/data/db mongo:latestThis command:
- Starts MongoDB in a Docker container named
mongodb. - Exposes port 27017 so your applications can connect to the database.
- Persists data on a Docker volume called
mongodbdata.
Option 2: If you already have MongoDB installed locally on your Linux machine, you can start it using the following command:
sudo systemctl start mongodThis will launch the MongoDB daemon as a system service. You can check its status with:
sudo systemctl status mongodIf MongoDB is not enabled to start automatically, you can enable it using:
sudo systemctl enable mongodCreating the database for the project:
Once MongoDB is running, open the Mongo shell with:
mongoshThen, create the database and collection (if needed) like this:
use social_media_dbThis creates a new database named social_media_db and an empty collection called users. You can now connect to this database using the DATABASE_URL in your .env file:
DATABASE_URL=mongodb://localhost:27017/social_media_dbEndpoints / Modules
This service offers the following functionalities:
Authentication
- POST /api/user/register: Register a new user. Requires username, email, and password.
- POST /api/user/login: Login with email and password. Returns an authentication token and sets an auth cookie with the generated token in the response headers.
User Profiles
- PUT /api/user/update: Update the authenticated user’s profile; requires authentication.
- POST /api/user/upload: Upload or update the authenticated user’s profile picture or files; requires authentication.
- GET /api/user/list/:page?: Retrieve a paginated list of users; requires authentication.
- GET /api/user/follows/:id/:page?: Retrieve a paginated list of users that a given user is following; requires authentication.
- GET /api/user/followers/:id/:page?: Retrieve a paginated list of users that follow the given user; requires authentication.
Posts
- POST /api/post/create: Create a new post; requires authentication and post content.
- DELETE /api/post/delete/:postId: Delete a post by ID; requires authentication and ownership.
- PUT /api/post/update/:postId: Edit a post; requires authentication and ownership.
Follow System
- POST /follow/{userId}: Follow a user; requires authentication.
- DELETE /follow/{userId}: Unfollow a user; requires authentication.
Examples
Register a new user
Create a new user account by sending form-urlencoded data with username, email, and password.
POST /api/user/register
Content-Type: application/x-www-form-urlencodedusername=johndoe&email=john@example.com&password=securePassword123{
"status": "success",
"message": "User registered successfully"
}Login user
Authenticate a user and receive a JWT token for authorized requests.
POST /api/user/login
Content-Type: application/x-www-form-urlencodedemail=john@example.com&password=securePassword123{
"status": "success",
"message": "User successfully login",
"data": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}Get list of users (paginated)
Retrieve a paginated list of users. Requires authorization cookie.
GET /api/user/list/1
Cookie: auth=<token>{
"status": "success",
"message": "App users list:",
"data": {
"limit": 2,
"hasPrevPage": false,
"hasNextPage": true,
"hasMore": true,
"docs": [
{
"_id": "683184a03f8095069a874db0",
"name": "joe",
"nick": "joe18"
},
{
"_id": "683184e13f8095069a874db4",
"name": "mathew",
"nick": "mathew78"
}
],
"totalDocs": 285,
"totalPages": 143,
"page": 1,
"pagingCounter": 1,
"nextPage": 2
}
}Update user
Update user sending update data.
PUT /api/user/update
Content-Type: application/x-www-form-urlencoded
Cookie: auth=<token>name=new_name&password=new_password&nick=new_nick{
"status": "success",
"message": "User updated"
}Upload user image
Upload an image file for the authenticated user.
POST /api/user/upload
Content-Type: multipart/form-data
Cookie: auth=<token>file0=[binary image file]{
"status": "success",
"message": "Image",
"data": {
"nick": "migus",
"image": "1748168965251tux.png"
}
}Get following users
Get the users that the specified user is following (paginated).
GET /api/user/follows/user_id_1234
Content-Type: application/json
Cookie: auth=<token>{
"status": "success",
"message": "Follows:",
"data": [
{
"_id": "683184e13f8095069a874db4",
"name": "jhon",
"nick": "jhon",
"image": "default.jpg"
},
...
],
"total": 20,
"pages": 2
}Get followers
Get the users that are following the specified user (paginated).
GET /api/user/followers/user_id_1234
Content-Type: application/json
Cookie: auth=<token>{
"status": "success",
"message": "Followers:",
"data": [
{
"user": {
"_id": "683184a03f8095069a874db0",
"name": "joe",
"nick": "joe18",
"image": "1748168965251tux.png"
}
},
...
]
}Create post
Create a new post with text content.
POST /api/post/create
Content-Type: application/x-www-form-urlencoded
Cookie: auth=<token>text=This+is+a+new+post{
"status": "success",
"message": "Post created successfully:",
"data": {
"user": "683184a03f8095069a874db0",
"text": "This is a new post",
"image": "",
"likes": [],
"comments": [],
"created_at": "2025-05-25T10:13:56.833Z",
"_id": "6832f95bf4f9ef462945ef38",
"__v": 0
}
}Delete post
Delete a specific post by its ID.
DELETE /api/post/delete/postId_6832f95bf4f9ef462945ef38
Content-Type: application/json
Cookie: auth=<token>{
"status": "success",
"message": "Post deleted successfully"
}Update post
Update the content of an existing post by its ID.
PUT /api/post/update/postId_6832f95bf4f9ef462945ef3c
Content-Type: application/x-www-form-urlencoded
Cookie: auth=<token>text=Updated+post+content{
"status": "success",
"message": "Post updated successfully:",
"data": {
"_id": "6832fbf9f4f9ef462945ef3c",
"user": "683184a03f8095069a874db0",
"text": "Updated post content",
"image": "",
"likes": [],
"comments": [],
"created_at": "2025-05-25T10:13:56.833Z",
"__v": 0
}
}Follow user
Follow a user by their ID.
POST /api/follow/usuario123
Content-Type: application/json
Cookie: auth=<token>{
"status": "success",
"message": "User followed successfully"
}Unfollow user
Unfollow a user by their ID.
DELETE /api/unfollow/usuario123
Content-Type: application/json
Cookie: auth=<token>{
"status": "success",
"message": "Unfollowed"
}Dependencies
Dependencies
- express: Minimalist framework for building APIs and web servers in Node.js.
- mongoose: Library for modeling MongoDB objects in Node.js, makes schema usage easier.
- mongoose-paginate-ts: Plugin for Mongoose that adds pagination with TypeScript support.
- cors: Middleware to enable CORS (Cross-Origin Resource Sharing).
- dotenv / @dotenvx/dotenvx: Load environment variables from `.env` files.
- cookie-parser: Parses cookies from incoming HTTP requests.
- bcrypt: Securely hashes passwords.
- jwt-simple: Encodes and decodes JWT tokens for authentication.
- moment: Handles and formats dates and times.
- multer: Middleware to handle file uploads (multipart/form-data).
- sqlite3: Lightweight embedded SQL database engine, useful for testing or small apps.
Dev Dependencies
- @types/*: TypeScript typings for JavaScript libraries.
- jest: Testing framework for JavaScript and TypeScript.
- supertest: Library for testing HTTP endpoints.
- ts-jest: Transforms TypeScript code so it can be tested with Jest.
- ts-node-dev: Runs TypeScript code with automatic reload for development.
Frequently Asked Questions
Q: Is this project production-ready?
A: It's designed for educational/demo purposes, but you can adapt it for real use.