VelocityJS is a blazing fast, feature-rich web framework that brings Next.js-like capabilities to vanilla JavaScript. With zero external dependencies, it provides powerful routing, state management, component system, and much more.
- HTML Page Fetching - Load HTML pages dynamically with AJAX
- Layout System - Nested layouts with content injection
- Head Management - Dynamic meta tags, titles, and SEO optimization
- Component System - Reusable components with lifecycle hooks
- Static Generation - Pre-render pages for better performance
- API Routes - Mock API endpoints for development
- Plugin Architecture - Extensible plugin system
- State Management - Built-in reactive state with Vuex-like API
- Theme System - Dark/light mode with auto-detection
- Internationalization - Multi-language support
- Error Boundaries - Graceful error handling
- Performance Monitoring - Web Vitals tracking
- Accessibility - ARIA support, focus management, screen reader compatibility
- Development Tools - Enhanced debugging and dev experience
- Request Caching - Intelligent response caching with TTL
- Offline Support - Queue requests when offline
- Request Interceptors - Transform requests/responses
- Rate Limiting - Prevent API abuse
- Mock Responses - Test with fake data
- File Upload/Download - Built-in file handling
npm install velocity-js-framework
Or use via CDN:
<script type="module">
import VelocityJS from 'https://cdn.jsdelivr.net/npm/velocity-js-framework/src/velocity.js';
</script>
import { createApp } from './src/velocity.js';
const app = createApp({
debug: true,
theme: 'auto',
baseURL: '/api'
});
// Define routes with enhanced options
app.route('/', () => '<h1>Welcome to VelocityJS v2.0!</h1>', {
title: 'Home Page',
meta: {
description: 'VelocityJS enhanced framework demo'
}
});
// Initialize the app
await app.init();
app.route('/about', null, {
fetchHtml: true,
htmlPath: '/pages/about.html',
title: 'About Us',
cache: true
});
// Register a component
app.component('UserCard', {
template: (props) => `
<div class="velocity-card">
<h3>${props.name}</h3>
<p>${props.email}</p>
</div>
`
});
// Use component in page
app.page('/user/[id]', 'UserCard', {
title: (context) => `User ${context.params.id}`,
head: {
meta: {
description: 'User profile page'
}
}
});
// Define a layout
app.router.addLayout('main', (context) => `
<!DOCTYPE html>
<html>
<head>
<title>${context.title || 'VelocityJS App'}</title>
</head>
<body>
<nav>...</nav>
<main>{{content}}</main>
<footer>...</footer>
</body>
</html>
`);
// Use layout in routes
app.route('/dashboard', dashboardHandler, {
layout: 'main',
title: 'Dashboard'
});
// Create a store
const store = app.createStore({
user: null,
posts: []
});
// Add mutations
store.mutations.set('setUser', (state, user) => {
state.user = user;
});
// Add actions
store.actions.set('fetchUser', async ({ commit }, userId) => {
const user = await app.network.get(`/users/${userId}`);
commit('setUser', user);
});
// Use in components
store.dispatch('fetchUser', 123);
// Create a plugin
const analyticsPlugin = {
name: 'analytics',
install(app, options) {
app.track = (event, data) => {
console.log('Analytics:', event, data);
};
}
};
// Use plugin
app.use(analyticsPlugin, { apiKey: 'your-key' });
// Set theme
app.setTheme('dark'); // 'light', 'dark', or 'auto'
// Listen for theme changes
app.events.on('theme:changed', (theme) => {
console.log('Theme changed to:', theme);
});
app.setHead({
title: 'My App',
meta: {
description: 'Amazing web application',
keywords: 'web, app, javascript',
'og:title': 'My App',
'og:description': 'Share description',
'twitter:card': 'summary'
},
link: {
canonical: 'https://myapp.com',
icon: '/favicon.ico'
}
});
// Add translations
app.i18n.addMessages('en', {
welcome: 'Welcome to {name}!',
goodbye: 'Goodbye, {name}!'
});
app.i18n.addMessages('es', {
welcome: 'Β‘Bienvenido a {name}!',
goodbye: 'Β‘AdiΓ³s, {name}!'
});
// Use translations
app.setLocale('es');
const message = app.t('welcome', { name: 'VelocityJS' });
// Cache responses for 5 minutes
const response = await app.network.get('/api/data', {
cache: true,
cacheTTL: 300000
});
// Add auth token to all requests
app.network.addRequestInterceptor((config) => {
config.headers.Authorization = `Bearer ${getToken()}`;
return config;
});
// Handle response errors
app.network.addResponseInterceptor(
(response) => response,
(error) => {
if (error.status === 401) {
app.navigate('/login');
}
return Promise.reject(error);
}
);
// Requests automatically queue when offline
const response = await app.network.post('/api/data', {
message: 'This will be sent when back online'
});
// Upload file with progress
await app.network.upload('/api/upload', formData, {
onProgress: (percent) => console.log(`Upload: ${percent}%`)
});
// Download file
await app.network.download('/api/file.pdf', {
filename: 'document.pdf'
});
VelocityJS includes a comprehensive CSS framework with:
- CSS Variables - Full theme customization
- Dark Mode - Automatic system preference detection
- Component Library - Buttons, forms, cards, modals, etc.
- Grid System - Flexible 12-column layout
- Utilities - Spacing, typography, colors
- Animations - Smooth transitions and effects
- Accessibility - WCAG compliant components
<div class="velocity-container">
<div class="velocity-row">
<div class="velocity-col-6">
<div class="velocity-card">
<div class="velocity-card-body">
<h5>Enhanced Card</h5>
<p>With theme support and animations</p>
<button class="velocity-btn velocity-btn-primary">
Action
</button>
</div>
</div>
</div>
</div>
</div>
app.route('/user/[id]', (context) => {
return `<h1>User ${context.params.id}</h1>`;
});
app.route('/blog/[...slug]', (context) => {
const path = context.params.slug;
return `<h1>Blog: ${path}</h1>`;
});
app.router.addGuard('/admin/*', (context) => {
if (!user.isAdmin) {
app.navigate('/login');
return false;
}
return true;
});
app.route('/dashboard', dashboardHandler, {
children: [
{ path: '/stats', handler: statsHandler },
{ path: '/users', handler: usersHandler }
]
});
app.router.addTransition('slide', {
out: async () => {
document.querySelector('#app').style.transform = 'translateX(-100%)';
await sleep(300);
},
in: async () => {
document.querySelector('#app').style.transform = 'translateX(0)';
}
});
app.route('/page', handler, { transition: 'slide' });
// Automatically tracks Core Web Vitals
app.performance.vitals; // { FCP, LCP, FID, CLS }
// Custom performance marks
app.addPerformanceMark('feature-start');
// ... code execution
const duration = app.measurePerformance('feature', 'feature-start', 'feature-end');
const stats = app.getStats();
console.log(stats.performance.memoryUsage);
const app = createApp({ debug: true });
// Enhanced logging
app.logger.time('route-render');
// ... code
app.logger.time('route-render').end();
// Component inspection
console.log(app.getStats());
app.errorBoundary.addErrorBoundary('user-component', {
fallback: (error) => `<div>Error loading user: ${error.message}</div>`
});
// Add mock responses for testing
app.network.addMockResponse('/api/users', 'GET', {
data: [{ id: 1, name: 'John Doe' }],
status: 200
});
// Test will use mock data
const users = await app.network.get('/api/users');
const app = createApp({
enableServiceWorker: true
});
// Automatically handles offline scenarios
// Queues requests when offline
// Syncs when back online
app.setHead({
meta: {
'Content-Security-Policy': "default-src 'self'; script-src 'self' 'unsafe-eval'"
}
});
// Automatic XSS protection in templates
app.component('SafeContent', {
template: (props) => app.utils.sanitizeHtml(props.content)
});
createApp(options)
- Create new VelocityJS instanceinit()
- Initialize the frameworkroute(path, handler, options)
- Add routepage(path, component, options)
- Add page componentcomponent(name, definition)
- Register componentuse(plugin, options)
- Add pluginnavigate(path, options)
- Navigate to routesetTheme(theme)
- Change themesetState(key, value)
- Set global stategetStats()
- Get performance statistics
addRoute(path, handler, options)
- Add route with full optionsaddLayout(name, template)
- Add layout templateaddGuard(path, guard)
- Add route guardaddTransition(name, config)
- Add page transitionpreloadRoute(path)
- Preload route for faster navigation
request(url, options)
- Make HTTP requestget/post/put/delete(url, data, options)
- HTTP methodsupload(url, formData, options)
- File uploaddownload(url, options)
- File downloadsetAuthToken(pattern, token)
- Set auth tokensaddRequestInterceptor(fn)
- Add request interceptorsetRateLimit(url, limit, window)
- Set rate limiting
set(key, value, options)
- Store dataget(key, defaultValue)
- Retrieve dataremove(key)
- Remove dataclear()
- Clear all datasetTTL(key, ttl)
- Set expirationencrypt/decrypt(data)
- Encrypt sensitive data
Check out the examples/
directory for:
- Basic SPA - Simple single-page application
- E-commerce App - Shopping cart with state management
- Blog Platform - Content management with routing
- Dashboard - Admin interface with components
- PWA Example - Progressive web app features
We welcome contributions! Please see our Contributing Guide for details.
MIT License - see LICENSE file for details.
- Inspired by Next.js, Vue.js, and modern web development practices
- Built with modern web standards and accessibility in mind
- Community-driven development
VelocityJS v2.0.0 - Where performance meets developer experience! π