Node.js for beginners: build your first API

Node.js runs JavaScript outside a browser, so you can use it to build servers, command-line tools and other applications. This guide takes you from installation to a working API, a server that returns information when another program asks for it.

The project gives you something concrete to discuss with recruiters. It is a learning project, not a production-ready application or a guarantee of a job or work authorization.

1. Install Node.js and check your tools

You need an internet connection, a code editor, a terminal and Git. Some JavaScript knowledge helps, especially variables, functions and objects. If those are new to you, follow the example and change one line at a time to see what happens.

Node.js is a cross-platform runtime, or software that runs JavaScript. It uses V8, the engine also used by Chrome, to compile JavaScript into machine code. Node.js includes npm, a package manager for installing reusable code. Despite a common assumption, npm is not an acronym for "Node Package Manager."

Use nvm, a Node version manager, to switch versions between projects without replacing your whole installation.

  • macOS and Linux: Open your terminal and follow the installation instructions in the official nvm repository. Use its current installation command rather than copying an old version from another tutorial.
  • Windows: Install Windows Subsystem for Linux using wsl --install in PowerShell, then complete the prompts to set up a Linux distribution. Open its terminal and follow the same nvm instructions. Keep this project and run its commands inside that Linux environment. The nvm mentioned above is not the native Windows version manager.

Restart the terminal or follow nvm's instructions to load it into your current shell. Then run:

sh
nvm install --lts
nvm use --lts
nvm alias default 'lts/*'

LTS means long-term support and is a good default for learning and collaboration. Current releases offer newer features sooner. For an existing project, use the version specified by the team instead:

sh
nvm install 22
nvm use 22

Here 22 is an illustrative version, not a recommendation to override a project's requirements.

Install Git using your operating system's installer or package manager, then verify the tools:

sh
node --version
npm --version
npx --version
git --version

Each command should print a version. npx runs package-provided commands. If a command is not found, reopen the terminal and check the installation instructions. If nvm is missing, check that its shell setup has loaded.

If you plan to publish using SSH, check for a key with ls -al ~/.ssh. If you need one, create it with ssh-keygen -t ed25519, then add the public key to your Git hosting account. For GitHub, test it with ssh -T [email protected]; check the host fingerprint before accepting it. A successful GitHub authentication message can still return a nonzero exit status. Never share your private key.

2. Run a JavaScript file

Create a project folder:

sh
mkdir node-starter
cd node-starter

Open it in your editor and create hello.js:

js
console.log("Hello from Node.js");

Run it:

sh
node hello.js

You should see Hello from Node.js. If the file is not found, check that the terminal is in the folder where you saved it.

You can also type node without a filename to open the interactive REPL and try expressions one at a time. Enter .exit to return to the terminal. A saved script is better when you want to run or share the same code again.

3. Create and run an Express API

In the same folder, run:

sh
npm init -y
npm install express
npm install --save-dev nodemon

Express helps you define routes, which are paths that connect requests to code. Nodemon is a development tool that restarts the server when you save changes.

Find the scripts section of package.json and replace it with:

json
"scripts": {
  "start": "node server.js",
  "dev": "nodemon server.js"
}

Create server.js:

js
const express = require("express");

const app = express();
const port = process.env.PORT || 3000;

app.get("/health", (request, response) => {
  response.json({ status: "ok" });
});

app.get("/api/profile", (request, response) => {
  response.json({
    skills: ["JavaScript", "Node.js"],
    learning: "Building a first API"
  });
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

Start it with npm run dev. In a browser, open http://localhost:3000/health and http://localhost:3000/api/profile. The first returns a status; the second returns a profile in JSON, a text format other programs can read.

When the browser requests /api/profile, Express finds the matching route, runs its function and sends the response. Change the learning text and save the file. Nodemon restarts the server, so you can refresh the page. Use Ctrl+C to stop it. For a normal start without automatic restarts, use npm start.

localhost means your own computer. process.env.PORT lets another environment choose the port; if it is unavailable, the example uses the local fallback. If that port is occupied, stop the other process or set PORT and visit the new address. The health route only shows that this process responds; it does not check a database or external service.

4. Add a localized date

An API for users around the world should distinguish an instant from the way a person sees it. Add this route before app.listen:

js
app.get("/api/event", (request, response) => {
  const instant = "2026-05-12T14:00:00.000Z";
  const timeZone = request.query.timeZone || "UTC";

  if (typeof timeZone !== "string") {
    return response.status(400).json({ error: "Invalid time zone" });
  }

  try {
    const display = new Intl.DateTimeFormat("en", {
      dateStyle: "full",
      timeStyle: "short",
      timeZone
    }).format(new Date(instant));

    return response.json({ instant, timeZone, display });
  } catch (error) {
    return response.status(400).json({ error: "Invalid time zone" });
  }
});

Visit http://localhost:3000/api/event?timeZone=Asia/Tokyo, then try timeZone=UTC. The illustrative event is the same instant, but the displayed time changes. An invalid time zone returns an error instead of crashing the server.

The Z marks the stored example as UTC. The display uses English and an explicit time zone; a real application should obtain the user's language and time zone rather than assume either. Do not put secrets or personal immigration details in these responses: anyone who can reach the API may be able to read them.

5. Manage packages and understand asynchronous code

package.json describes the project and its dependencies. package-lock.json records the resolved dependency tree; commit both so others can reproduce the installation. Do not commit node_modules. Create a .gitignore containing:

text
node_modules/
.env

Useful commands in the project folder:

sh
npm install
npm ci
npm outdated
npm audit

npm install installs dependencies and can update the lockfile. npm ci requires a matching lockfile and replaces node_modules with a clean installation, making it useful in automated builds. npm outdated shows available updates; npm audit reports known dependency vulnerabilities. Review what is affected and test updates instead of blindly applying breaking fixes.

Versions commonly follow semantic versioning: major.minor.patch. Major updates may break compatibility; minor updates add compatible features; patches generally fix issues. A range such as ^1.2.3 permits compatible updates within that major version, with special rules for versions starting with zero. The lockfile records what was actually resolved.

Node can start an I/O operation, such as reading a file, and work on other requests while it waits. The event loop runs JavaScript callbacks when work is ready; Node uses underlying facilities, including libuv, to coordinate asynchronous operations. JavaScript execution can still block that loop: a long calculation or synchronous file read in a request handler delays other requests.

Older APIs often use an error-first callback: the first argument is an error, if one occurred.

js
const fs = require("node:fs");

fs.readFile("hello.js", "utf8", (error, text) => {
  if (error) return console.error(error.message);
  console.log(text);
});

A promise represents a result that will arrive later. async/await lets you handle it with familiar error handling:

js
const fs = require("node:fs/promises");

async function showFile() {
  try {
    const text = await fs.readFile("hello.js", "utf8");
    console.log(text);
  } catch (error) {
    console.error(error.message);
  }
}

showFile();

Run either example from the project folder. Prefer asynchronous I/O in request handlers; await does not make a CPU-heavy calculation non-blocking.

This project uses CommonJS, with require. ES modules use import and are selected through configuration such as "type": "module" in package.json, or an .mjs extension. For an existing repository, follow its module style and tooling. For a new project, choose ES modules if your runtime and dependencies support them; use CommonJS when compatibility or the team's existing setup calls for it. Do not switch syntax without changing the configuration.

The asynchronous JavaScript guide covers these patterns in more detail.

6. Make the project useful in an international job search

Put the project in a Git repository with a README that states the Node version used, installation and start commands, sample URLs, and limitations. Explain the time-zone decision and how you tested it. Use sample data you are comfortable publishing.

A recruiter-facing description could say, if accurate:

Built a Node.js and Express API with health and profile routes. Added time-zone-aware event formatting and documented how to run and test it locally.

Link the repository from your international job-search profile. A reviewer should be able to identify your contribution and reproduce it without waiting for a message across time zones.

Search job boards and employer career pages for combinations such as Node.js, backend, visa sponsorship and relocation assistance. Read each listing's location and work-authorization requirements; sponsorship wording may describe eligibility rather than a commitment to sponsor every applicant. Ask the recruiter which roles offer support and what the process covers. Use the salary negotiation guide when discussing an offer.

A portfolio can demonstrate skills; it cannot establish work eligibility or secure sponsorship. For advice about your individual immigration situation, consult a qualified immigration professional.

Next, prioritize JavaScript functions and async error handling, then Express input validation and automated tests. Add a database when you can explain the API without one; learn TypeScript and Docker as the roles you target require them. Use actual job descriptions to decide what to study first, rather than assuming every international team uses the same stack.

The Pro section adds a tested take-home extension, Docker packaging and an automated build workflow.

Pro: turn the API into a reviewable take-home exercise

This exercise adds a route that accepts an instant and time zone, validates both and returns a localized display. It also separates the app from the listening server so tests can start it on an available port.

1. Add the route and export the app

In server.js, add this route before the final app.listen block:

js
app.get("/api/format-time", (request, response) => {
  const { instant, timeZone } = request.query;

  if (typeof instant !== "string" || typeof timeZone !== "string") {
    return response.status(400).json({
      error: "Provide instant and timeZone as strings"
    });
  }

  const date = new Date(instant);

  // Require the exact UTC ISO format produced by toISOString().
  if (Number.isNaN(date.getTime()) || date.toISOString() !== instant) {
    return response.status(400).json({
      error: "Use a valid UTC ISO instant"
    });
  }

  try {
    const display = new Intl.DateTimeFormat("en", {
      dateStyle: "full",
      timeStyle: "short",
      timeZone
    }).format(date);

    return response.json({ instant, timeZone, display });
  } catch (error) {
    return response.status(400).json({ error: "Invalid time zone" });
  }
});

Replace the existing app.listen block with:

js
if (require.main === module) {
  app.listen(port, () => {
    console.log(`Server listening on port ${port}`);
  });
}

module.exports = app;

When you run node server.js, the server starts as before. When a test imports the file, it receives the app without automatically opening the usual port.

The strict ISO check is a deliberate contract: it rejects ambiguous local dates and alternative representations. A production API might accept more formats, but should define and test them explicitly. The route formats a supplied instant; it does not resolve ambiguous local times when clocks change.

Try it with the server running:

sh
curl "http://localhost:3000/api/format-time?instant=2026-05-12T14%3A00%3A00.000Z&timeZone=UTC"

Change UTC to Not_A_Zone to see a 400 response. The response text may vary with the runtime's locale data, so clients should not parse the display string as a date.

2. Add automated tests

Create test/server.test.js. The test uses Node's built-in test runner and starts the app on a temporary local port:

js
const test = require("node:test");
const assert = require("node:assert/strict");
const app = require("../server");

test("formats a valid instant and rejects invalid input", async () => {
  const server = app.listen(0, "127.0.0.1");
  await new Promise((resolve) => server.once("listening", resolve));

  try {
    const base = `http://127.0.0.1:${server.address().port}`;
    const params = new URLSearchParams({
      instant: "2026-05-12T14:00:00.000Z",
      timeZone: "UTC"
    });

    const valid = await fetch(`${base}/api/format-time?${params}`);
    const body = await valid.json();
    assert.equal(valid.status, 200);
    assert.equal(body.instant, "2026-05-12T14:00:00.000Z");
    assert.equal(body.timeZone, "UTC");
    assert.equal(typeof body.display, "string");

    params.set("timeZone", "Not_A_Zone");
    const invalidZone = await fetch(`${base}/api/format-time?${params}`);
    assert.equal(invalidZone.status, 400);

    params.set("timeZone", "UTC");
    params.set("instant", "not-a-date");
    const invalidDate = await fetch(`${base}/api/format-time?${params}`);
    assert.equal(invalidDate.status, 400);
  } finally {
    await new Promise((resolve, reject) => {
      server.close((error) => error ? reject(error) : resolve());
    });
  }
});

Add "test": "node --test" to the scripts object in package.json, with a comma after the preceding script. Run:

sh
npm test

The test checks the contract rather than asserting the exact localized string. Extend it with missing parameters and repeated query parameters before presenting the route as more than a learning exercise.

Pro: package and deploy with Docker and CI

Build and run the container

Create a Dockerfile in the project root:

dockerfile
FROM node:lts-slim

WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev

COPY server.js ./
ENV NODE_ENV=production
EXPOSE 3000
CMD ["node", "server.js"]

Create .dockerignore:

text
node_modules
.git
.env

With Docker installed and running:

sh
docker build -t node-starter .
docker run --rm -p 3000:3000 node-starter

Open http://localhost:3000/health, then stop the container with Ctrl+C. The image installs production dependencies from the lockfile; nodemon is not needed to run the server.

The node:lts-slim tag can change. For a reproducible team build, choose a supported Node version that matches the project and pin the image version or digest. Retest when updating it.

Run tests on each push

For a repository hosted on GitHub, create .github/workflows/ci.yml:

yaml
name: Test and build

on:
  push:
  pull_request:

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: lts/*
          cache: npm
      - run: npm ci
      - run: npm test
      - run: docker build -t node-starter .

Commit the workflow, lockfile, tests and Dockerfile, then push the repository. Check the workflow's run and fix failures before sharing it. For repeatability, configure CI and the Docker image to use the same project-approved Node version instead of floating LTS references. Review action versions and pin them according to your team's security policy.

Deploy without exposing secrets

Choose a container host and follow its instructions to build from the repository or publish the image to its registry. Configure the service to use the port supplied by the host through PORT; the app already reads it. After deployment, request the public /health URL and test /api/format-time with sample data.

Do not commit registry credentials, tokens or private user data. Set secrets through the host's secret-management interface if the project later needs them. A public demo also needs production work, such as appropriate request limits, monitoring and a review of its error handling.

In your README, add the test command, the sample request, the Docker command and the demo URL only after you have verified them. Describe the strict timestamp contract and what remains unfinished. That gives a reviewer evidence they can inspect rather than a claim that the project is production-ready.