0
0
Node.jsframework~5 mins

API versioning strategies in Node.js

Choose your learning style9 modes available
Introduction

API versioning helps keep your app working well when you add new features or fix bugs. It lets old and new users use the API without problems.

You want to add new features without breaking old apps using your API.
You need to fix bugs but keep old API behavior for existing users.
You want to support multiple app versions at the same time.
You plan to improve your API but want a smooth transition for users.
You want to clearly communicate changes to API users.
Syntax
Node.js
1. URL versioning:
   GET /api/v1/resource

2. Query parameter versioning:
   GET /api/resource?version=1

3. Header versioning:
   GET /api/resource
   Headers: Accept-Version: v1

4. Content negotiation:
   GET /api/resource
   Headers: Accept: application/vnd.myapp.v1+json

URL versioning is the simplest and most visible way.

Header and content negotiation keep URLs clean but need client support.

Examples
URL versioning uses the version number in the path.
Node.js
GET /api/v1/users
GET /api/v2/users
Query parameter versioning sends the version as a URL parameter.
Node.js
GET /api/users?version=1
GET /api/users?version=2
Header versioning sends the version in a custom header.
Node.js
GET /api/users
Headers: Accept-Version: v1

GET /api/users
Headers: Accept-Version: v2
Content negotiation uses the Accept header to specify version.
Node.js
GET /api/users
Headers: Accept: application/vnd.myapp.v1+json

GET /api/users
Headers: Accept: application/vnd.myapp.v2+json
Sample Program

This example shows URL versioning with two versions of a greeting API. Version 1 returns a simple message. Version 2 returns a new message. Both work side by side.

Node.js
import express from 'express';
const app = express();

// Version 1 route
app.get('/api/v1/greet', (req, res) => {
  res.send('Hello from API version 1');
});

// Version 2 route
app.get('/api/v2/greet', (req, res) => {
  res.send('Hello from API version 2 with new features');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

Choose a versioning strategy that fits your users and app needs.

Keep old versions running until users can switch to new ones.

Document your API versions clearly for easy use.

Summary

API versioning helps manage changes without breaking users.

Common ways: URL path, query params, headers, or content negotiation.

URL versioning is easiest to understand and implement.