Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,14 +45,23 @@ jobs:
run: npm run build

generated-project:
name: Generated project - ${{ matrix.package-manager }}, Node ${{ matrix.node-version }}
name: Generated project - ${{ matrix.package-manager }}, Node ${{ matrix.node-version }} ${{ matrix.features }}
runs-on: ubuntu-latest
needs: cli
strategy:
fail-fast: false
matrix:
node-version: [22, 24, 26]
package-manager: [npm, pnpm]
features: ['--gatekeeper']
# The project without extras must keep working as features are added.
include:
- node-version: 24
package-manager: npm
features: '--no-gatekeeper'
- node-version: 24
package-manager: pnpm
features: '--no-gatekeeper'

steps:
- name: Checkout
Expand All @@ -79,7 +88,7 @@ jobs:
git config --global user.email "ci@example.com"

- name: Scaffold a project
run: node dist/index.js test-api --yes --package-manager ${{ matrix.package-manager }}
run: node dist/index.js test-api --yes --package-manager ${{ matrix.package-manager }} ${{ matrix.features }}

- name: Everything is committed, including the lockfile
working-directory: test-api
Expand Down Expand Up @@ -113,6 +122,13 @@ jobs:
echo "Malformed JSON status: $status"
test "$status" = "400"

# Rate limit headers only when Gatekeeper was chosen.
if [ "${{ matrix.features }}" = "--gatekeeper" ]; then
curl -sI http://localhost:3000/api/health | grep -qi '^x-ratelimit-limit: 100'
else
! curl -sI http://localhost:3000/api/health | grep -qi '^x-ratelimit-limit'
fi

docker:
name: Docker image - ${{ matrix.package-manager }}
runs-on: ubuntu-latest
Expand Down
10 changes: 8 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
## [1.1.0] - 2026-11-09

### Added

- Interactive setup: project name, Gatekeeper rate limiting and package manager. `--yes` takes the defaults, any option passed on the command line isn't asked, and it never asks in CI.
- Optional rate limiting with [Gatekeeper](https://github.com/SibilSoren/gatekeeper) 2: 100 requests a minute per IP, added by default. `--gatekeeper` / `--no-gatekeeper` choose without asking.

### Fixed

Expand Down Expand Up @@ -35,7 +40,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added

- `typecheck` script, `.dockerignore`, `.nvmrc` and tests for validation, error handling and Swagger in generated projects.
- CI scaffolds a project with npm and pnpm on Node 22, 24 and 26, then builds, tests, lints, boots the production build and builds the Docker image. It also runs weekly to catch dependency changes.
- CI scaffolds a project with npm and pnpm on Node 22, 24 and 26, with and without Gatekeeper, then builds, tests, lints, boots the production build and builds the Docker image. It also runs weekly to catch dependency changes.
- CLI tests that scaffold every combination of options and check the generated files, so a new option can't change what the others produce.

## [1.0.0] - 2026-06-09

Expand Down
9 changes: 7 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Scaffold a production-ready **Node.js + TypeScript + Express** API with a single
npx create-api-starterkit my-api
```

**Zero prompts. Zero config. Just works.**
Answer two questions, or add `--yes` to take the defaults. Requires Node.js 22.12 or later.

## What You Get

Expand All @@ -26,6 +26,7 @@ A fully configured API project with:
- 🐳 **Docker** β€” multi-stage Dockerfile + docker-compose
- 🎨 **ESLint + Prettier** β€” consistent code style
- πŸͺ **Husky + lint-staged** β€” git hooks for quality
- 🚦 **Rate limiting** (optional) β€” [Gatekeeper](https://github.com/SibilSoren/gatekeeper), 100 requests a minute per IP by default

## Quick Start

Expand All @@ -51,9 +52,13 @@ npx create-api-starterkit <project-name> [options]

| Option | Description | Default |
|---|---|---|
| `-y, --yes` | Skip the questions and use the defaults | asks |
| `--gatekeeper` / `--no-gatekeeper` | Add or skip Gatekeeper rate limiting | add |
| `--package-manager <pm>` | Use `npm` or `pnpm` | `npm` |
| `--skip-install` | Skip dependency installation | `false` |
| `--no-git` | Skip git initialization | `false` |
| `--package-manager <pm>` | Use `npm` or `pnpm` | `npm` |

Any option you pass on the command line isn't asked again. In CI (when `CI` is set), it never asks.

## Generated Project Structure

Expand Down
12 changes: 10 additions & 2 deletions docs/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>create-api-starterkit β€” Scaffold Production-Ready APIs in Seconds</title>
<meta name="description" content="One command to scaffold a production-ready Node.js + TypeScript + Express API. Zero config. Zero prompts. Just works." />
<meta name="description" content="One command to scaffold a production-ready Node.js + TypeScript + Express API. Two questions, or --yes for the defaults." />
<meta name="keywords" content="nodejs, typescript, express, api, scaffolding, cli, boilerplate, starter, template" />
<meta name="author" content="SibilSoren" />

Expand Down Expand Up @@ -54,7 +54,7 @@ <h1 class="hero-title animate-in delay-1">
<span class="hero-gradient">in seconds.</span>
</h1>
<p class="hero-subtitle animate-in delay-2">
One command. Zero prompts. Zero config.<br />
One command. Two questions, or <code>--yes</code> for the defaults.<br />
A fully configured Node.js + TypeScript + Express API β€” ready to build on.
</p>
<div class="hero-terminal animate-in delay-3">
Expand Down Expand Up @@ -195,6 +195,14 @@ <h3>You're live!</h3>
<div class="cli-options">
<h3>CLI Options</h3>
<div class="options-table">
<div class="option-row">
<code>-y, --yes</code>
<span>Skip the questions and use the defaults</span>
</div>
<div class="option-row">
<code>--no-gatekeeper</code>
<span>Skip Gatekeeper rate limiting (added by default)</span>
</div>
<div class="option-row">
<code>--skip-install</code>
<span>Skip dependency installation</span>
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "create-api-starterkit",
"version": "1.0.0",
"version": "1.1.0",
"description": "Scaffold a production-ready Node.js + TypeScript + Express API with a single command",
"type": "module",
"bin": {
Expand Down
64 changes: 25 additions & 39 deletions src/create.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ import {
installCommand,
runCommand,
} from './utils/package-manager.js';
import {
GATEKEEPER_PACKAGE,
GATEKEEPER_VERSION,
injectGatekeeper,
} from './utils/gatekeeper.js';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
Expand All @@ -35,7 +40,7 @@ export async function createProject(options: CreateOptions): Promise<void> {
}

// ─── Check target directory ─────────────────────────────
const targetDir = path.resolve(process.cwd(), projectName);
const targetDir = path.resolve(options.cwd ?? process.cwd(), projectName);

if (!isDirEmpty(targetDir)) {
log.error(`Directory "${projectName}" already exists and is not empty.`);
Expand Down Expand Up @@ -77,38 +82,21 @@ export async function createProject(options: CreateOptions): Promise<void> {
const pkg = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8'));

if (options.includeGatekeeper) {
pkg.dependencies = pkg.dependencies || {};
pkg.dependencies['@sibilsoren/gatekeeper'] = '^1.0.0';
}

if (options.includePrisma) {
pkg.dependencies = pkg.dependencies || {};
pkg.devDependencies = pkg.devDependencies || {};
pkg.dependencies['@prisma/client'] = '^5.10.0';
pkg.devDependencies['prisma'] = '^5.10.0';
pkg.scripts = pkg.scripts || {};
pkg.scripts['db:push'] = 'npx prisma db push';
pkg.scripts['db:studio'] = 'npx prisma studio';
pkg.dependencies = sortKeys({
...pkg.dependencies,
[GATEKEEPER_PACKAGE]: GATEKEEPER_VERSION,
});
}
fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2));

fs.writeFileSync(packageJsonPath, JSON.stringify(pkg, null, 2) + '\n');
}

// Inject Gatekeeper into app.ts
if (options.includeGatekeeper) {
const appTsPath = path.join(targetDir, 'src', 'app.ts');
if (fs.existsSync(appTsPath)) {
let appTs = fs.readFileSync(appTsPath, 'utf-8');
appTs = appTs.replace(
"import { healthRoutes } from './modules/health/health.routes.js';",
"import { healthRoutes } from './modules/health/health.routes.js';\nimport gatekeeper from '@sibilsoren/gatekeeper';"
);
appTs = appTs.replace(
"// ─── Request Logging ──────────────────────────────────────\n app.use(requestLogger);",
"// ─── Request Logging ──────────────────────────────────────\n app.use(requestLogger);\n\n // ─── Rate Limiting ────────────────────────────────────────\n app.use(gatekeeper({ limit: 100, window: 60 }));"
);
fs.writeFileSync(appTsPath, appTs);
}
fs.writeFileSync(
appTsPath,
injectGatekeeper(fs.readFileSync(appTsPath, 'utf-8')),
);
}

if (packageManager === 'pnpm') {
Expand Down Expand Up @@ -167,17 +155,6 @@ export async function createProject(options: CreateOptions): Promise<void> {
printCommandOutput(error);
log.warning(`Fix the error above, then run "${installCmd}" in the project directory.`);
}

if (options.includePrisma) {
log.step(++currentStep, totalSteps + 1, 'Initializing Prisma...');
try {
const prismaCmd = packageManager === 'pnpm' ? 'pnpm dlx prisma init' : 'npx prisma init';
execSync(prismaCmd, { cwd: targetDir, stdio: 'ignore' });
log.success('Prisma initialized');
} catch {
log.warning('Failed to initialize Prisma. Run "npx prisma init" manually.');
}
}
}

// ─── Initial commit ─────────────────────────────────────
Expand Down Expand Up @@ -223,6 +200,15 @@ export async function createProject(options: CreateOptions): Promise<void> {
log.blank();
}

/**
* Sort an object's keys, the way npm keeps dependency lists.
*/
function sortKeys(object: Record<string, string>): Record<string, string> {
return Object.fromEntries(
Object.entries(object).sort(([a], [b]) => a.localeCompare(b)),
);
}

/**
* Print the tail of a failed command's output, so the user sees why it failed.
*/
Expand Down
27 changes: 12 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import * as p from '@clack/prompts';
import { createProject } from './create.js';
import type { CreateOptions } from './types.js';
import { log } from './utils/logger.js';
import { validateProjectName } from './utils/validate.js';
import { PACKAGE_MANAGERS, isPackageManager } from './utils/package-manager.js';

// package.json sits one level up from both src/ and dist/.
Expand All @@ -22,6 +23,8 @@ program
.option('--skip-install', 'Skip installing dependencies', false)
.option('--no-git', 'Skip git initialization')
.option('--package-manager <pm>', `Package manager to use (${PACKAGE_MANAGERS.join(', ')})`)
.option('--gatekeeper', 'Add Gatekeeper rate limiting (default)')
.option('--no-gatekeeper', 'Skip Gatekeeper rate limiting')
.option('-y, --yes', 'Skip prompts and use defaults')
.action(async (projectNameArg: string | undefined, opts: Record<string, unknown>) => {
console.log();
Expand All @@ -41,8 +44,7 @@ program
skipInstall: opts.skipInstall as boolean,
noGit: !opts.git,
packageManager: isPackageManager(opts.packageManager) ? opts.packageManager : 'npm',
includeGatekeeper: false,
includePrisma: false,
includeGatekeeper: (opts.gatekeeper as boolean | undefined) ?? true,
};
await createProject(options);
return;
Expand All @@ -58,21 +60,17 @@ program
message: 'What is the name of your project?',
placeholder: 'my-awesome-api',
defaultValue: 'my-api',
validate: (val) => {
if (!val) return 'Project name is required';
},
// Empty means the default name; anything else must be a valid package name.
validate: (val) => (val ? validateProjectName(val).message : undefined),
});
},
includeGatekeeper: () =>
p.confirm({
message: 'Would you like to include Gatekeeper (Distributed Rate Limiter)?',
includeGatekeeper: () => {
if (opts.gatekeeper !== undefined) return Promise.resolve(opts.gatekeeper as boolean);
return p.confirm({
message: 'Add rate limiting with Gatekeeper? (100 requests a minute per IP, easy to change)',
initialValue: true,
}),
includePrisma: () =>
p.confirm({
message: 'Would you like to scaffold Prisma ORM?',
initialValue: true,
}),
});
},
packageManager: () => {
if (opts.packageManager) return Promise.resolve(opts.packageManager as string);
return p.select({
Expand All @@ -96,7 +94,6 @@ program
noGit: !opts.git,
packageManager: isPackageManager(project.packageManager) ? project.packageManager : 'npm',
includeGatekeeper: project.includeGatekeeper as boolean,
includePrisma: project.includePrisma as boolean,
};

await createProject(options);
Expand Down
4 changes: 2 additions & 2 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ export interface CreateOptions {
packageManager: PackageManager;
/** Include Gatekeeper rate limiter */
includeGatekeeper: boolean;
/** Include Prisma ORM */
includePrisma: boolean;
/** Directory to create the project in (default: the current directory) */
cwd?: string;
}
36 changes: 36 additions & 0 deletions src/utils/gatekeeper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
export const GATEKEEPER_PACKAGE = '@sibilsoren/gatekeeper';
export const GATEKEEPER_VERSION = '^2.0.0';

// Each anchor must match the template's src/app.ts exactly.
const IMPORT_ANCHOR =
"import { healthRoutes } from './modules/health/health.routes.js';";
const MIDDLEWARE_ANCHOR =
' // ─── Request Logging ──────────────────────────────────────\n app.use(requestLogger);\n';

const MIDDLEWARE = `
// ─── Rate Limiting ────────────────────────────────────────
// 100 requests per minute per client IP, counted in memory. Running more
// than one server? Share the count with a RedisStore:
// https://github.com/SibilSoren/gatekeeper#redis-store-distributed
app.use(gatekeeper({ limit: 100, window: '1m' }));
`;

/**
* Add Gatekeeper rate limiting to the template's app.ts, right after request
* logging so rate-limited requests are still logged. Throws if the template
* no longer matches, so a template change can't silently skip it.
*/
export function injectGatekeeper(appTs: string): string {
for (const anchor of [IMPORT_ANCHOR, MIDDLEWARE_ANCHOR]) {
if (!appTs.includes(anchor)) {
throw new Error(`app.ts template changed; can't find: ${anchor}`);
}
}

return appTs
.replace(
IMPORT_ANCHOR,
`${IMPORT_ANCHOR}\nimport { gatekeeper } from '${GATEKEEPER_PACKAGE}';`,
)
.replace(MIDDLEWARE_ANCHOR, `${MIDDLEWARE_ANCHOR}${MIDDLEWARE}`);
}
Loading
Loading