Skip to content

Node Backend Setup

We’re using a Node.js backend instead of a framework like Next.js because it gives you full control and works with any type of app — web, mobile, tools, or extensions. It’s simple, reliable, and matches how most production backends are built.

Next.js is great for some use cases, but serverless functions can get tricky with file uploads or long-running processes. A standalone Node backend keeps things straightforward.


Let’s create a home for your backend:

Terminal window
mkdir node-backend
cd node-backend

Initialize a fresh Node.js project:

Terminal window
npm init -y

Create your environment file:

Terminal window
touch .env

This sets up a basic package.json and an .env file where you’ll store your API key safely.


Install the packages you need:

Terminal window
npm install express cors dotenv openai multer

Install development tools:

Terminal window
npm install -D nodemon

What each package does:

  • express - Web server for your API
  • cors - Allows frontend to connect to your backend
  • dotenv - Loads secret keys from .env
  • openai - Connects to OpenAI’s API
  • multer - Handles file uploads
  • nodemon - Auto-restarts server while you develop

Update package.json to use modern JavaScript and add run scripts:

{
"type": "module",
"scripts": {
"start": "node index.js",
"dev": "nodemon index.js"
}
}

What this does:

  • "type": "module" - Lets you use import instead of require
  • start script - Runs your server in production
  • dev script - Runs with auto-restart when you save files

Add your API key and port in .env:

OPENAI_API_KEY=your_api_key_here
PORT=8000

Never commit this file — add .env to .gitignore.


Create index.js:

import express from "express";
import { config } from "dotenv";
import cors from "cors";
config();
const app = express();
const port = process.env.PORT || 8000;
app.use(cors());
app.use(express.json());
app.get("/", (req, res) => {
res.send("Backend is running successfully.");
});
app.listen(port, () => {
console.log(`🚀 Server running on http://localhost:${port}`);
});

Run the server:

Terminal window
npm run dev

Visit: http://localhost:8000

You should see:

Backend is running successfully.

IssueFix
Cannot use importAdd "type": "module" to package.json
Port in useChange PORT in .env file
Missing packagesRun npm install
Permission denied on .envCreate the file manually

Your backend is ready to connect to OpenAI. Next, you’ll build your first AI endpoint and make a real API call.

Let’s start building something smart! 🧠