@sarthakp/backpack
v1.0.2
Published
A lightweight, auto-CRUD backend framework built on Express and Zod.
Maintainers
Readme
🎒 Backpack Framework Documentation
Welcome to the official documentation for Backpack — a lightweight, modular, and fast Node.js framework built on top of Express. Backpack is designed to accelerate backend development by providing auto-generated CRUD routes, robust OpenAPI documentation, and a powerful plugin system.
Table of Contents
- Introduction
- Getting Started
- Core Configuration
- Models and Routing
- Database Adapters
- Authentication
- Plugins
- CLI Reference
Introduction
Backpack aims to reduce the boilerplate required to set up a production-ready Node.js backend. By simply defining your data models using Zod or Drizzle schemas, Backpack automatically generates robust CRUD endpoints and interactive Swagger documentation, letting you focus on your core business logic.
Getting Started
Installation
To scaffold a new Backpack project, you can use the official create-backpack CLI tool:
npx create-backpack my-app
cd my-app
npm install
npm run devYour Backpack development server will start, typically running on http://localhost:3000.
Core Configuration
A Backpack application is initialized using the backpack() function. You can pass a BackpackConfig object to configure port settings, middleware (like CORS), and load plugins.
import { backpack } from "@sarthakp/backpack";
import cors from "cors";
const app = backpack({
port: 3000,
cors: { origin: "*" }, // Built-in CORS support
plugins: [
// Array of Backpack plugins
]
});
app.start();Models and Routing
Backpack handles routing via an Express router wrapper. However, its most powerful feature is Auto-CRUD Generation.
Defining Models
You can define models using plain objects (which are converted to Zod schemas internally), raw Zod schemas, or Drizzle ORM tables.
import { z } from "zod";
const UserSchema = z.object({
name: z.string(),
email: z.string().email(),
age: z.number().optional()
});
// app.model(name, schema, autogenerateCrud, basePath)
app.model("User", UserSchema, true, "/api");Auto-Generated Endpoints
By setting autogenerate: true, Backpack will instantly generate the following endpoints and wire them up to your database (if a DB adapter is configured):
POST /api/users- Create a new userGET /api/users- List all usersGET /api/users/:id- Get user by IDPUT /api/users/:id- Update user by IDDELETE /api/users/:id- Delete user by ID
OpenAPI / Swagger UI
Backpack uses @asteasolutions/zod-to-openapi to automatically generate Swagger documentation based on your models.
Once your app is running, visit http://localhost:3000/docs to view and interact with your API documentation!
Custom Routing
You can still create custom routes easily:
// Standard routing
app.get("/hello", (req, res) => {
res.json({ message: "Hello from Backpack!" });
});
// Protected routes (Requires Auth Plugin)
app.post("/secure-data", true, (req, res) => {
res.json({ data: "This is secure data for authenticated users." });
});Database Adapters
Backpack currently supports multiple database targets through a unified DbAdapter interface.
MongoDB Adapter
import { DatabasePlugin, MongoAdapter } from "@sarthakp/backpack";
const app = backpack({
plugins: [
DatabasePlugin(new MongoAdapter("mongodb://localhost:27017/mydb"))
]
});PostgreSQL (Drizzle) Adapter
import { DatabasePlugin, PgAdapter } from "@sarthakp/backpack";
import { drizzle } from "drizzle-orm/node-postgres";
import { Pool } from "pg";
const pool = new Pool({ connectionString: "postgres://user:pass@localhost:5432/mydb" });
const db = drizzle(pool);
const app = backpack({
plugins: [
DatabasePlugin(new PgAdapter(db))
]
});Authentication
Backpack provides an out-of-the-box authentication plugin that supports Email/Password (using JWT and Argon2) and OAuth Providers.
import { authPlugin } from "@sarthakp/backpack";
import { GoogleProvider } from "@sarthakp/backpack";
const app = backpack({
plugins: [
authPlugin("MY_SUPER_SECRET_JWT_KEY", [
new GoogleProvider(clientId, clientSecret, redirectUri)
])
]
});Auth Endpoints
When the authPlugin is loaded, it automatically provides:
POST /auth/signup- Create a new user account (hashes password viaargon2).POST /auth/login- Verify credentials and return a JWT.GET /auth/:providerId- Redirect to OAuth provider (e.g., Google).GET /auth/:providerId/callback- Handle OAuth callback and return JWT.
Protecting Routes
To protect a route, pass true as the last argument to any route definition (or explicitly use the protect middleware):
app.get("/profile", true, (req, res) => {
// req.user contains the decoded JWT payload
res.json({ email: req.user.email });
});Plugins
Backpack's architecture is plugin-driven. A plugin is a function that receives the BackpackContext (which holds the Express app, config, DB services, and models) and can run logic on initialization or extend the app.
Writing a Custom Plugin
import { BackpackPlugin } from "@sarthakp/backpack";
export const MyCustomPlugin = (): BackpackPlugin => (ctx) => {
return {
onStart: () => {
console.log("My Custom Plugin has started!");
},
extendApp: {
myCustomMethod: () => "Hello!"
}
};
};CLI Reference
The Backpack CLI helps you move fast by generating code and managing databases.
backpack init <name>
Scaffolds a new Backpack application in a directory named <name>.
backpack generate model <name> (Alias: g model)
Generates a new data model boilerplate file in src/models/.
Example: backpack g model user creates src/models/User.ts.
backpack dev
Starts the development server in watch mode using tsup.
backpack build
Builds the project for production, generating minified ESM output in /dist.
Database Commands
backpack db push: Rapid prototyping. Pushes schema changes directly to the database without generating migration files (via Drizzle Kit).backpack db generate: Generates SQL migration files based on schema changes.backpack db migrate: Runs pending migrations against the database. Looks for a custom script atsrc/db/migrate.ts, or falls back to standard drizzle-kit.
