Introducing HazelJS: The Next-Gen JavaScript Runtime
Discover the vision and technology behind HazelJS, a blazing fast, secure, and developer-friendly JavaScript runtime.
Introduction
HazelJS is a modern, lightweight, enterprise-grade Node.js framework designed for building scalable server-side applications. With a monorepo architecture, built-in AI integration, and enterprise security features, HazelJS empowers developers to build production-ready applications faster than ever before.
Monorepo Architecture
HazelJS is organized as a modular monorepo with 11+ independent packages. Install only what you need:
# Core framework (required)
npm install @hazeljs/core reflect-metadata
# Optional packages - install only what you need
npm install @hazeljs/ai # AI integration
npm install @hazeljs/cache # Multi-tier caching
npm install @hazeljs/websocket # Real-time communication
npm install @hazeljs/serverless # Serverless adapters
npm install @hazeljs/prisma # Prisma ORM integration
npm install @hazeljs/auth # JWT authentication
npm install @hazeljs/config # Configuration management
npm install @hazeljs/swagger # API documentation
npm install @hazeljs/cron # Scheduled tasks
npm install -D @hazeljs/cli # CLI toolCore Framework Features
1. Advanced Dependency Injection
Enterprise-grade DI with three scopes: Singleton, Transient, and Request. Automatic circular dependency detection included.
import { Injectable, Scope } from '@hazeljs/core';
// Singleton (default) - one instance for entire app
@Injectable()
export class UserService {
// Shared across all requests
}
// Transient - new instance every time
@Injectable({ scope: Scope.TRANSIENT })
export class LoggerService {
// Fresh instance for each injection
}
// Request - one instance per HTTP request
@Injectable({ scope: Scope.REQUEST })
export class RequestContextService {
// Isolated per request
}2. Decorator-Based API
Clean, intuitive programming model with decorators for controllers, routes, and more.
import { Controller, Get, Post, Body, Param } from '@hazeljs/core';
import { HazelModule } from '@hazeljs/core';
@Controller('/users')
export class UserController {
@Get()
findAll() {
return { users: [] };
}
@Get('/:id')
findOne(@Param('id') id: string) {
return { id, name: 'John Doe' };
}
@Post()
create(@Body() createUserDto: CreateUserDto) {
return { message: 'User created', data: createUserDto };
}
}
@HazelModule({
controllers: [UserController],
})
export class AppModule {}3. Built-in Validation
Automatic request validation using class-validator decorators.
import { IsEmail, IsString, MinLength } from 'class-validator';
export class CreateUserDto {
@IsEmail()
email: string;
@IsString()
@MinLength(8)
password: string;
@IsString()
name: string;
}
@Controller('/users')
export class UserController {
@Post()
create(@Body() createUserDto: CreateUserDto) {
// Automatically validated before reaching here
return createUserDto;
}
}Built-in AI Integration
HazelJS includes first-class AI integration with support for OpenAI, Anthropic, Gemini, Cohere, and Ollama. Build AI-powered applications effortlessly.
Basic AI Service Usage
import { Injectable } from '@hazeljs/core';
import { AIService, AITask } from '@hazeljs/ai';
@Injectable()
export class ChatService {
constructor(private aiService: AIService) {}
@AITask({
name: 'chat',
prompt: 'You are a helpful assistant. Respond to: {{input}}',
provider: 'openai',
model: 'gpt-4',
outputType: 'string',
stream: true,
})
async chat(message: string): Promise<string> {
return message; // Decorator handles AI execution
}
}Enhanced AI Service with Multiple Providers
import { AIEnhancedService } from '@hazeljs/ai';
const aiService = new AIEnhancedService();
// Use OpenAI
const response = await aiService.complete({
messages: [{ role: 'user', content: 'Hello!' }],
model: 'gpt-4',
provider: 'openai',
});
// Use Ollama for local LLMs
const localResponse = await aiService.complete({
messages: [{ role: 'user', content: 'Hello!' }],
model: 'llama2',
provider: 'ollama',
});
// Streaming support
for await (const chunk of aiService.streamComplete({
messages: [{ role: 'user', content: 'Tell me a story' }],
provider: 'openai',
})) {
console.log(chunk.delta);
}Enterprise Security
Production-ready security middleware included out of the box. No configuration needed—secure by default.
Security Headers Middleware
import { SecurityHeadersMiddleware } from '@hazeljs/core';
// Automatically applies:
// - X-Content-Type-Options: nosniff
// - X-Frame-Options: DENY
// - X-XSS-Protection: 1; mode=block
// - Referrer-Policy: no-referrer-when-downgrade
// - Strict-Transport-Security (production only)
app.useGlobalMiddleware(new SecurityHeadersMiddleware());Rate Limiting
import { RateLimitMiddleware } from '@hazeljs/core';
app.useGlobalMiddleware(
new RateLimitMiddleware({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100, // 100 requests per window
message: 'Too many requests, please try again later.',
})
);CSRF Protection
import { CsrfMiddleware } from '@hazeljs/core';
app.useGlobalMiddleware(
new CsrfMiddleware({
secret: process.env.CSRF_SECRET,
methods: ['POST', 'PUT', 'PATCH', 'DELETE'],
excludePaths: ['/api/webhooks'], // Exclude webhook endpoints
})
);Input Sanitization
import { sanitizeStringInput, sanitizeObject } from '@hazeljs/core';
// Sanitize strings
const clean = sanitizeStringInput(userInput);
// Sanitize entire objects
const cleanData = sanitizeObject(requestBody);Multi-Tier Caching
Smart caching system with memory, Redis, and CDN support. Automatic cache invalidation and tag-based management.
import { Cache, CacheKey, CacheTTL, CacheEvict } from '@hazeljs/cache';
@Controller('/products')
export class ProductController {
@Get('/:id')
@Cache({
strategy: 'memory',
ttl: 3600, // 1 hour
key: 'product-{id}',
})
async getProduct(@Param('id') id: string) {
// Expensive database query - cached for 1 hour
return await this.productService.findOne(id);
}
@Post()
@CacheEvict({ keys: ['product-*'] }) // Invalidate all product caches
async createProduct(@Body() dto: CreateProductDto) {
return await this.productService.create(dto);
}
@Get('/featured')
@Cache({
strategy: 'redis',
ttl: 1800,
tags: ['products', 'featured'],
})
async getFeatured() {
return await this.productService.findFeatured();
}
}WebSocket & Real-time Communication
Built-in WebSocket support with room management, Server-Sent Events, and scalable real-time features.
import { WebSocketGateway, OnConnect, OnDisconnect, OnMessage, Subscribe } from '@hazeljs/websocket';
import { WebSocketClient, Data } from '@hazeljs/websocket';
@WebSocketGateway({ path: '/notifications' })
export class NotificationGateway {
@OnConnect()
handleConnection(client: WebSocketClient) {
console.log('Client connected:', client.id);
}
@OnDisconnect()
handleDisconnect(client: WebSocketClient) {
console.log('Client disconnected:', client.id);
}
@OnMessage('join-room')
handleJoinRoom(client: WebSocketClient, @Data() data: { room: string }) {
client.join(data.room);
client.emit('joined', { room: data.room });
}
@Subscribe('chat')
handleChat(client: WebSocketClient, @Data() message: string) {
// Broadcast to all clients in the same room
client.to(client.room).emit('message', {
from: client.id,
message,
});
}
}Serverless Support
Deploy to AWS Lambda, Google Cloud Functions, and other serverless platforms with zero configuration changes.
import { Serverless } from '@hazeljs/serverless';
import { createLambdaHandler } from '@hazeljs/serverless';
@Controller('/api')
export class ApiController {
@Get('/hello')
@Serverless({ optimize: true })
hello() {
return { message: 'Hello from serverless!' };
}
}
// AWS Lambda handler
export const handler = createLambdaHandler(AppModule);
// Google Cloud Functions handler
export const cloudFunction = createCloudFunctionHandler(AppModule);Prisma Integration
First-class ORM support with repository pattern, automatic migrations, and type-safe database access.
import { PrismaService, BaseRepository, PrismaModel } from '@hazeljs/prisma';
import { Injectable } from '@hazeljs/core';
@PrismaModel('User')
export class UserRepository extends BaseRepository {
// Automatic CRUD operations
// Custom methods
async findByEmail(email: string) {
return this.prisma.user.findUnique({ where: { email } });
}
}
@Injectable()
export class UserService {
constructor(private userRepo: UserRepository) {}
async create(data: CreateUserDto) {
return this.userRepo.create({ data });
}
}Automatic API Documentation
Generate OpenAPI documentation automatically with Swagger UI integration.
import { Swagger, ApiOperation } from '@hazeljs/swagger';
import { SwaggerModule } from '@hazeljs/swagger';
@Controller('/users')
@Swagger({
title: 'User API',
description: 'User management endpoints',
version: '1.0.0',
})
export class UserController {
@Get()
@ApiOperation({
summary: 'Get all users',
description: 'Returns a list of all users',
tags: ['users'],
})
findAll() {
return { users: [] };
}
}
// Enable Swagger UI at /api-docs
SwaggerModule.setRootModule(AppModule);Testing Support
Full testing utilities with test module builder, provider overrides, and isolated testing environments. 90%+ test coverage across packages.
import { TestingModule } from '@hazeljs/core';
describe('UserController', () => {
let module: TestingModule;
let controller: UserController;
beforeEach(async () => {
module = await TestingModule.create({
controllers: [UserController],
providers: [
{
provide: UserService,
useValue: {
findAll: jest.fn().mockResolvedValue([{ id: 1, name: 'Test' }]),
},
},
],
});
controller = module.get(UserController);
});
it('should return users', async () => {
const result = await controller.findAll();
expect(result).toEqual([{ id: 1, name: 'Test' }]);
});
});Complete Example
Here's a complete example showing multiple features working together:
import 'reflect-metadata';
import { HazelApp, HazelModule, Controller, Get, Post, Body } from '@hazeljs/core';
import { AIModule, AIService, AITask } from '@hazeljs/ai';
import { CacheModule } from '@hazeljs/cache';
import { PrismaModule } from '@hazeljs/prisma';
import { SwaggerModule } from '@hazeljs/swagger';
import { SecurityHeadersMiddleware } from '@hazeljs/core';
@Controller('/api/jobs')
export class JobController {
constructor(
private aiService: AIService,
private jobService: JobService
) {}
@Post('/enhance')
@Cache({ strategy: 'memory', ttl: 3600 })
async enhanceJob(@Body() jobDesc: string) {
return this.jobService.enhanceJobDescription(jobDesc);
}
}
@HazelModule({
imports: [AIModule, CacheModule, PrismaModule],
controllers: [JobController],
providers: [JobService],
})
export class AppModule {}
async function bootstrap() {
const app = new HazelApp(AppModule);
// Apply security middleware
app.useGlobalMiddleware(new SecurityHeadersMiddleware());
// Enable Swagger
SwaggerModule.setRootModule(AppModule);
await app.listen(3000);
console.log('🚀 Server running on http://localhost:3000');
console.log('📚 API docs at http://localhost:3000/api-docs');
}
bootstrap();Why Choose HazelJS?
- Monorepo Architecture: 11+ modular packages. Install only what you need.
- Built-in AI: Native support for OpenAI, Anthropic, Gemini, Cohere, and Ollama.
- Enterprise Security: Security headers, rate limiting, CSRF protection, and input sanitization out of the box.
- Zero Configuration: Sensible defaults. Start building immediately.
- Type-Safe: Full TypeScript support with excellent IDE experience.
- Production-Ready: 90%+ test coverage, comprehensive documentation, and battle-tested features.
Getting Started
Ready to build with HazelJS? Get started in minutes:
# Install core package
npm install @hazeljs/core reflect-metadata
# Create your first controller
# See code examples above
# Start building!Conclusion
HazelJS combines the best of modern Node.js frameworks with unique features like built-in AI integration, enterprise security, and a modular architecture. Whether you're building APIs, real-time applications, or AI-powered services, HazelJS provides the tools you need to ship faster and with confidence.
Join our growing community and start building the next generation of Node.js applications today!