How to Build and Deploy a Node.js API from Scratch

Category: Software Install and Setup

Building and deploying an API with Node.js is a crucial skill for modern web development. Whether you're working on a personal project or a production-ready service, this guide will walk you through creating and deploying a Node.js API step by step.

1. Setting Up Your Development Environment

Before writing any code, ensure you have the following installed:

  • Node.js (Download from nodejs.org)
  • npm or yarn (comes with Node.js installation)
  • A code editor (VS Code is recommended)

2. Initializing a Node.js Project

mkdir node-api && cd node-api
npm init -y

This creates a package.json file, which manages dependencies.

3. Installing Dependencies

Install Express.js to handle API routes:

npm install express cors dotenv

4. Creating the Express Server

Create an index.js file and add the following code:

const express = require('express');
const cors = require('cors');
const app = express();

app.use(cors());
app.use(express.json());

app.get('/', (req, res) => {
	res.json({ message: 'Welcome to our API' });
});

app.listen(3000, () => {
	console.log('Server running on port 3000');
});

5. Adding API Routes

Create a routes.js file and define API endpoints:

const express = require('express');
const router = express.Router();

router.get('/users', (req, res) => {
	res.json([{ id: 1, name: 'John Doe' }, { id: 2, name: 'Jane Doe' }]);
});

module.exports = router;

Import the routes into index.js:

const userRoutes = require('./routes');
app.use('/api', userRoutes);

6. Testing the API

Start the server:

node index.js

Test endpoints using Postman or by visiting http://localhost:3000/api/users.

7. Deploying the API

Using Heroku

Install the Heroku CLI and run:

heroku create my-node-api
heroku git:remote -a my-node-api
git add .
git commit -m "Deploy API"
git push heroku main

Using Vercel

npm install -g vercel
vercel

Conclusion

Congratulations! You've successfully built and deployed a Node.js API. Continue exploring authentication, database integration, and scaling strategies to enhance your API further.

For more details, visit the official Node.js documentation.