Package Exports
- @nitronjs/framework
Readme
NitronJS
A modern and extensible Node.js MVC framework built on Fastify. NitronJS focuses on clean architecture, modular structure, and developer productivity, offering built-in routing, middleware, configuration management, CLI tooling, and native React integration for scalable full-stack applications.
Features
- MVC Architecture - Clean separation of concerns with Models, Views, and Controllers
- React SSR - Built-in React server-side rendering with TypeScript support
- Fast & Lightweight - Built on Fastify for high performance
- CLI Tools - Powerful command-line interface for scaffolding and development
- Database ORM - Intuitive query builder and model system for MySQL
- Hot Reload - Development mode with automatic reloading
- Middleware System - Flexible middleware pipeline with route-specific middleware
- Session Management - Built-in session support with multiple drivers
- Security - CSRF protection, authentication, and input validation
- Modern Build System - esbuild + PostCSS + Tailwind CSS integration
Installation
Create a new NitronJS project:
npx @nitronjs/framework my-app
cd my-appDependencies are installed automatically during project creation.
Quick Start
Configure your database in
config/database.jsRun migrations:
npx njs migrate --seed- Start development server:
npm run devYour application will be running at http://localhost:3000
CLI Commands
NitronJS comes with a powerful CLI tool (njs):
Development & Build
njs dev # Start development server with hot reload
njs build # Build views for production
njs start # Start production serverDatabase
njs migrate # Run pending migrations
njs migrate:fresh # Drop all tables and re-run migrations
njs migrate:fresh --seed # Drop, migrate, and seed
njs seed # Run database seedersCode Generation
njs make:controller <name> # Generate a new controller
njs make:model <name> # Generate a new model
njs make:middleware <name> # Generate a new middleware
njs make:migration <name> # Generate a new migration
njs make:seeder <name> # Generate a new seederUtilities
njs storage:link # Create symbolic link for storageProject Structure
my-app/
├── app/
│ ├── Controllers/ # Request handlers
│ ├── Middlewares/ # Custom middleware
│ └── Models/ # Database models
├── config/ # Configuration files
│ ├── app.js
│ ├── database.js
│ └── server.js
├── database/
│ ├── migrations/ # Database migrations
│ └── seeders/ # Database seeders
├── public/ # Static assets
├── resources/
│ ├── css/ # Stylesheets
│ └── views/ # React components (TSX)
├── routes/
│ └── web.js # Route definitions
└── storage/ # File storageRouting
Define routes in routes/web.js:
import { Route } from '@nitronjs/framework';
import HomeController from '#app/Controllers/HomeController.js';
Route.get('/', HomeController.index).name('home');
Route.get('/about', HomeController.about);
Route.post('/contact', HomeController.contact);Route Groups & Middleware
Route.prefix('/admin').middleware('auth').group(() => {
Route.get('/dashboard', AdminController.dashboard);
Route.get('/users', AdminController.users);
});Controllers
Create controllers with njs make:controller:
class HomeController {
static async index(request, reply) {
return reply.view('Site/Home', {
title: 'Welcome'
});
}
static async contact(request, reply) {
const { name, email } = request.body;
// Handle contact form
return reply.redirect('/thank-you');
}
}
export default HomeController;Views (React SSR)
Create React views in resources/views/:
// resources/views/Site/Home.tsx
export default function Home({ title, items }) {
return (
<html>
<head>
<title>{title}</title>
<link rel="stylesheet" href="/css/site_style.css" />
</head>
<body>
<h1>{title}</h1>
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</body>
</html>
);
}Views are automatically compiled and bundled with your application.
Models
Create models with njs make:model:
import { Model } from '@nitronjs/framework';
export default class User extends Model {
static table = 'users';
static primaryKey = 'id';
}Query Examples
// Find all users
const users = await User.get();
// Find by ID
const user = await User.find(1);
// Where clauses
const admins = await User.where('role', '=', 'admin').get();
// Create new record
const user = new User();
user.name = 'John';
user.email = 'john@example.com';
await user.save();
// Update
await User.where('id', '=', 1).update({
name: 'Jane'
});
// Delete
await User.where('id', '=', 1).delete();Middleware
Create middleware with njs make:middleware:
class CheckAge {
static async handler(req, res) {
const age = req.query.age;
if (age < 18) {
return res.status(403).send('Access denied');
}
// If no return, continues to next middleware/handler
}
}
export default CheckAge;Register middleware in app/Kernel.js:
export default {
routeMiddlewares: {
"check-age": CheckAge,
}
};Apply to routes:
Route.middleware('check-age').get('/restricted', Controller.method);Database Migrations
Create migrations with njs make:migration:
import { Schema } from '@nitronjs/framework';
class CreateUsersTable {
static async up() {
await Schema.create('users', (table) => {
table.id();
table.string('name');
table.string('email').unique();
table.string('password');
table.timestamp('created_at');
table.timestamp('updated_at').nullable();
});
}
static async down() {
await Schema.dropIfExists('users');
}
}
export default CreateUsersTable;Configuration
All configuration files are in the config/ directory:
- app.js - Application settings (name, env, debug mode)
- database.js - Database connections
- server.js - Server configuration (port, host, CORS)
- session.js - Session management
- auth.js - Authentication settings
- hash.js - Hashing algorithm configuration
Access config values:
import { Config } from '@nitronjs/framework';
const appName = Config.get('app.name');
const dbHost = Config.get('database.host');Session Management
// Set session data
req.session.set('user', { id: 1, name: 'John' });
// Get session data
const user = req.session.get('user');
// Check if session has value
if (req.session.get('user')) {
// User is logged in
}
// Remove session data
req.session.set('user', null);
// Get all session data
const allData = req.session.all();
// Regenerate session (security - after login)
req.session.regenerate();
// Flash messages (one-time)
req.session.flash('message', 'Success!');
const message = req.session.getFlash('message');
// CSRF token
const token = req.session.getCsrfToken();Authentication
Built-in authentication system (request-based):
// Attempt login (inside controller or middleware)
const success = await req.auth.attempt({
email: 'admin@example.com',
password: 'secret'
});
// veya belirli bir guard ile:
// const success = await req.auth.guard('user').attempt({ email, password });
// Kullanıcıya erişim
const user = await req.auth.user();
// veya
// const user = await req.auth.guard('user').user();
// Giriş yapmış mı?
if (req.auth.check()) {
// Authenticated
}
// Çıkış
await req.auth.logout();
// veya
// await req.auth.guard('user').logout();Validation
import { Validator } from '@nitronjs/framework';
const validation = Validator.make(req.body, {
email: 'required|email',
password: 'required|string|min:8',
age: 'required|numeric|min:18'
});
if (validation.fails()) {
return res.status(422).send({
errors: validation.errors()
});
}Environment Variables
Create a .env file in your project root:
APP_NAME=nitronjs
APP_DEV=true
APP_DEBUG=true
APP_PORT=3000
APP_URL=http://localhost
DATABASE_DRIVER=mysql
DATABASE_HOST=127.0.0.1
DATABASE_PORT=3306
DATABASE_NAME=nitronjs
DATABASE_USERNAME=root
DATABASE_PASSWORD=Response Methods
// Render view
return res.view('Site/Home', { title: 'Welcome' });
// JSON response
return res.json({ success: true, data: users });
// Redirect
return res.redirect('/dashboard');
// Status code
return res.status(404).send('Not Found');
// Download file
return res.download('/path/to/file.pdf');Testing Your Application
Build and run in production mode:
npm run build
npm run startRequirements
- Node.js 18.x or higher
- MySQL 5.7+ or MariaDB 10.3+
License
ISC