⚡ Quickstart
This hands-on tutorial gets you from zero to running API in less than 5 minutes.
We will create a minimal Express server exposing the ready-made Authentication Service and User Service backed by MongoDB.
📋 Prerequisites
Before we start, make sure you have the following installed on your system:
- Node.js (v18 or higher)
- Docker and Docker Compose (for MongoDB)
- npm or yarn (package manager)
1️⃣ Create Project Directory
First, create a new directory for your quickstart project and navigate into it:
mkdir quickstart
cd quickstart
2️⃣ Install Dependencies
npm install express@^4.19.0 mongodb @nodeblocks/backend-sdk
npm install -D typescript ts-node @types/node @types/express@^4.17.0
📝 Important: Don't forget to add your
.npmrc
file with the authentication token to access the private @nodeblocks/backend-sdk package.
⚠️ Compatibility: The Nodeblocks Backend SDK is compatible with Express v4.x and requires TypeScript for optimal development experience.
Using Local Development Version
If you need to use the latest local development version of the SDK, follow these steps:
- Clone and build the SDK locally:
git clone <sdk-repository-url>
cd nodeblocks-backend-sdk
npm install
npm run build
npm link
- In your quickstart project, link to the local version:
npm link @nodeblocks/backend-sdk
- To switch back to the published version:
npm unlink @nodeblocks/backend-sdk
npm install @nodeblocks/backend-sdk
3️⃣ Initialize TypeScript
Create a TypeScript configuration file to enable proper compilation and type checking:
npx tsc --init
This will generate a tsconfig.json
file. You can use the default configuration, or customize it according to your project needs.
4️⃣ Setup MongoDB with Docker Compose
Create docker-compose.yml
in your project root directory with following content:
services:
mongodb:
image: mongo:7
container_name: mongodb
ports:
- "27017:27017"
restart: always
environment:
MONGO_INITDB_DATABASE: dev
💡 Security Note: For production environments, you can protect your database by adding authentication. Include
MONGO_INITDB_ROOT_USERNAME
andMONGO_INITDB_ROOT_PASSWORD
environment variables in your Docker Compose configuration.
Start MongoDB in detached mode:
docker-compose up -d
5️⃣ Bootstrap the Server
Create /index.ts
with the minimal setup to run both authentication and user services:
import express from 'express';
import { middlewares, services, drivers } from '@nodeblocks/backend-sdk';
const { nodeBlocksErrorMiddleware } = middlewares;
const { authService, userService } = services;
const { getMongoClient } = drivers;
const client = getMongoClient('mongodb://localhost:27017', 'dev');
// Authentication Service - handles user registration, login, and token management
express()
.use(
authService(
{
identities: client.collection('identities'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
},
),
userService(
{
users: client.collection('users'),
identities: client.collection('identities'),
},
{
authSecrets: {
authEncSecret: 'your-encryption-secret',
authSignSecret: 'your-signing-secret',
},
}
)
)
.use(nodeBlocksErrorMiddleware())
.listen(8089, () => console.log('Server running on http://localhost:8089'));
⚠️ Critical: The
nodeBlocksErrorMiddleware()
is essential! Without it, your API will return HTML error pages instead of JSON responses when errors occur. Always include it after your services.
🔑 Authentication Setup: The authentication service provides endpoints for user registration, login, and invitation management. The user service requires valid authentication tokens to access its endpoints.
6️⃣ Build and Run the Server
Compile the TypeScript code and start the server:
npx tsc
node index.js
You should see the following output:
Server running on http://localhost:8089
Your API server is now running with both authentication and user services!
7️⃣ Test the Authentication Flow
Step 1: Register a User
First, create a user account through the authentication service:
curl -X POST http://localhost:8089/auth/register \
-H 'Content-Type: application/json' \
-d '{
"email": "user@example.com",
"password": "securepassword123"
}'
Step 2: Login to Get Access Token
Login with the registered user to get an access token:
curl -X POST http://localhost:8089/auth/login \
-H 'Content-Type: application/json' \
-d '{
"email": "user@example.com",
"password": "securepassword123"
}'
You should receive a response with an access, refresh tokens and identity id:
{
"accessToken": "77c268e06d87594067d91c5b2f08e532...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"id": "f792cde5-958b-49e9-bf83-13d59c1e35c0"
}
Step 3: Use the Access Token
Now you can use the access token to access the user service endpoints:
# Create user profile
curl -X POST http://localhost:8089/users/ \
-H 'Authorization: Bearer <access-token>' \
-H 'Content-Type: application/json' \
-d '{"email":"user@example.com","name":"John","status":"active"}'
You should receive a JSON response similar to the following:
{
"id": "922ebcee-159f-4c92-8f2c-2599d7ed1680",
"email": "user@example.com",
"name": "John",
"status": "active",
"createdAt": "2025-06-18T06:19:55.974Z",
"updatedAt": "2025-06-18T06:19:55.974Z"
}
🚨 Understanding Error Handling
Try making an invalid request to see the error middleware in action:
# Missing required fields - triggers validation error
curl -X POST http://localhost:8089/users \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <bearer-token-from-auth-service>' \
-d '{"email":"john@example.com"}'
With nodeBlocksErrorMiddleware()
(✅ Correct):
{
"error": {
"message": "Validation Error",
"data": [
"request body must have required property 'name'",
"request body must have required property 'status'"
]
}
}
Without nodeBlocksErrorMiddleware()
(❌ Wrong):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>NodeblocksError: Validation Error<br> --error stack--</pre>
</body>
</html>
💡 Key Point: The error middleware transforms all errors into consistent JSON responses, making your API client-friendly.
🎉 What You've Built
Congratulations! ✨ You now have a fully-featured REST API with:
- Authentication system with user registration and login
- JWT token management with access and refresh tokens
- CRUD operations for users (Create, Read, Update, Delete)
- Automatic validation using JSON Schema
- MongoDB integration with proper connection handling
- JSON error responses with proper HTTP status codes
- TypeScript support for type safety
🔗 Available Endpoints
Authentication Service (/auth
)
POST /auth/register
- Register a new userPOST /auth/login
- Login and get access tokenPOST /auth/logout
- Logout and invalidate tokens
User Service (/users
) - Requires Authentication
POST /users
- Create a new user (admin only)GET /users
- List all users (admin only)GET /users/:userId
- Get user by ID (admin or self)PATCH /users/:userId
- Update user (admin or self)DELETE /users/:userId
- Delete user (admin or self)POST /users/:userId/lock
- Lock a user account (admin only)POST /users/:userId/unlock
- Unlock a user account (admin only)
🔐 Authentication Flow
- Register a user account via
/auth/register
- Login to get access and refresh tokens via
/auth/login
- Use access token in
Authorization: Bearer <token>
header for protected endpoints
➡️ Next Steps
- Create a Custom Service - Learn to build your own services
- Schema Concepts - Understand data validation
- Handler Patterns - Master business logic organization