Skip to content

Best Practices

Organize your project for maintainability:

my-project/
├── src/
│ ├── config/
│ ├── utils/
│ └── index.js
├── tests/
└── package.json

Keep configuration separate:

config/app.js
export default {
name: process.env.APP_NAME || 'My App',
debug: process.env.DEBUG === 'true',
timeout: parseInt(process.env.TIMEOUT || '5000')
};
// index.js
import config from './config/app.js';
import { createApp } from 'your-package-name';
const app = createApp(config);

Always handle errors gracefully:

async function safeRun() {
try {
await app.run();
} catch (error) {
console.error('Error:', error.message);
// Fallback behavior
await app.runSafeMode();
}
}

Implement proper logging:

import { createApp } from 'your-package-name';
const app = createApp({
name: 'My App',
logger: {
level: 'info',
format: 'json'
}
});

Write comprehensive tests:

import { createApp } from 'your-package-name';
import { describe, it, expect } from 'vitest';
describe('App', () => {
it('should create app instance', () => {
const app = createApp({ name: 'Test' });
expect(app.name).toBe('Test');
});
});

Always validate user input:

function validateConfig(config) {
if (!config.name || typeof config.name !== 'string') {
throw new Error('Invalid name');
}
if (config.timeout && config.timeout < 0) {
throw new Error('Invalid timeout');
}
return config;
}
const app = createApp(validateConfig(userConfig));

Clean up resources properly:

async function runWithCleanup() {
const app = createApp({ name: 'My App' });
try {
await app.run();
} finally {
await app.stop();
await app.cleanup();
}
}

Following these best practices will help you:

  • Write maintainable code
  • Handle errors gracefully
  • Ensure security
  • Optimize performance