Skip to content
forms-raw_singleitemedit-icon
navigation
modification_btn
docs
messages
flatprojectmap.handlebars
Plugin - index.js
modificationbutton
docs_htmltables.handlebars

Plugin - index.js

docs_html.handlebars
documentation.handlebars

Plugin index.js — What it Does (Generic App Plugin)

The index.js file is the entry point for a plugin. It declares the plugin’s identity, registers routes, wires controllers and views, exposes configuration defaults, and provides lifecycle hooks so the host app can mount/unmount the plugin cleanly.

Primary Responsibilities

  • Manifest: Export name, version, description, and optional capabilities.
  • Router: Create and export an Express Router (or equivalent) that maps HTTP endpoints to controllers.
  • Controllers & Models: Import controller handlers and (optionally) initialize data models.
  • Views: Point to the plugin’s views/ (and views/partials/) for server-rendered pages if used.
  • Static Assets: Optionally expose a public/ directory for CSS/JS/images under a predictable mount path.
  • Config Defaults: Provide sane defaults and a schema for plugin settings (env or DB-backed).
  • Permissions: Declare required roles/permissions for protected routes.
  • Lifecycle Hooks: Export init(app, opts) and shutdown() for startup/teardown logic.
  • Events/Jobs: (Optional) Register background jobs or subscribe to app-wide events.

Typical Exports

The module usually returns an object that the host uses to mount the plugin:

// index.js (generic shape)
                    const path = require('path');
                    const express = require('express');
                    
                    const controllers = require('./controllers');       // e.g., { list, getOne, create, update, remove }
                    const { requireRole } = require('../_shared/auth'); // optional: shared auth middleware
                    
                    const router = express.Router();
                    
                    // Routes (examples)
                    router.get('/', controllers.list);
                    router.get('/:id', controllers.getOne);
                    router.post('/', requireRole('editor'), controllers.create);
                    router.put('/:id', requireRole('editor'), controllers.update);
                    router.delete('/:id', requireRole('admin'), controllers.remove);
                    
                    // Lifecycle hooks
                    async function init(app, opts = {}) {
                      const basePath = opts.basePath || '/plugins/[plugin-name]';
                    
                      // Views (optional)
                      if (opts.viewEngine) {
                        app.set('views', [
                          app.get('views'),
                          path.join(__dirname, 'views')
                        ]);
                      }
                    
                      // Static assets (optional)
                      app.use(`${basePath}/static`, express.static(path.join(__dirname, 'public')));
                    
                      // Mount router
                      app.use(basePath, router);
                    
                      // Models / DB init (optional)
                      // await connectModels(opts.db);
                    
                      // Events / Jobs (optional)
                      // subscribeToEvents(opts.eventBus);
                      // scheduleJobs(opts.scheduler);
                    
                      return { mountedAt: basePath };
                    }
                    
                    async function shutdown() {
                      // Clean up timers, listeners, db connections if any
                      // await disconnectModels();
                    }
                    
                    // Plugin manifest & settings
                    module.exports = {
                      name: '[plugin-name]',
                      version: '1.0.0',
                      description: 'Generic plugin that demonstrates a standard structure.',
                      capabilities: ['routes', 'views', 'static'],
                      configDefaults: {
                        enabled: true,
                        basePath: '/plugins/[plugin-name]',
                        permissions: {
                          create: ['editor', 'admin'],
                          update: ['editor', 'admin'],
                          remove: ['admin']
                        }
                      },
                      router,
                      init,
                      shutdown
                    };
                    

Route Map (Example)

Method Path Handler Auth/Role Purpose
GET / controllers.list Public/Viewer List records / index view
GET /:id controllers.getOne Public/Viewer Fetch a single record
POST / controllers.create Editor+ Create a record
PUT /:id controllers.update Editor+ Update a record
DELETE /:id controllers.remove Admin Delete a record

Integration Points

  • Mount Path: The host app calls init(app, { basePath }) to mount the plugin.
  • Auth: If the app provides middleware (e.g., requireRole), wire it on protected routes.
  • Views: Add the plugin’s views/ folder to the app’s view search paths when needed.
  • Assets: Serve public/ at {basePath}/static for plugin-specific JS/CSS/images.
  • Config: Merge configDefaults with environment/app config for runtime options.

Lifecycle

  1. Load: Host requires the module and reads manifest fields.
  2. Initialize: Host calls init(), plugin registers routes, views, and assets.
  3. Operate: Controllers handle incoming requests; models persist data.
  4. Shutdown: Host calls shutdown() to release resources.

Minimal Checklist

  • Exports: name, version, router, init(), shutdown()
  • Routes map to controller functions
  • Optional: views path added if server-rendered templates are used
  • Optional: static assets mounted under /static
  • Config defaults and permissions declared

Use this as a template to describe any plugin’s index.js in the codebase. Replace [plugin-name] and tailor routes, permissions, and lifecycle steps to the plugin’s purpose.

Controllers must use a consistent export structure to ensure proper router configuration. If a controller exports its functions directly, import it normally using const controller = require('./controller'). If a controller wraps its methods inside a named object (for example, module.exports = { controllerName: { index, save, edit } }), then destructure the import using const { controllerName } = require('./controller'). Mixing these patterns causes undefined route callbacks and runtime errors such as “Route.get() requires a callback function but got undefined.” To avoid this, standardize all controller exports—either export the function set directly or consistently wrap them in named objects—and match the import pattern accordingly in the router setup.

Routing & Export Note

All plugins must follow a consistent app.use() pattern for mounting Express routers into the main application. Each plugin should export its router directly using:

module.exports = router;

This approach ensures compatibility with the main application's mounting structure and avoids initialization conflicts that occur when exporting multiple objects or functions.

Directory & Namespacing Structure

Each plugin must include a namespaced view directory that matches its plugin name. For example:

plugins/ └─ falcon/ ├─ controllers/ ├─ models/ ├─ views/ │ ├─ falcon/ ← All Handlebars templates here (e.g. index.handlebars) │ └─ partials/ ← Namespaced partials registered as "falcon/<partial>" └─ index.js ← Exports Express router via module.exports 

This structure prevents view collisions across plugins (e.g., multiple index.handlebars files) and allows explicit rendering using namespaced paths like:

res.render('falcon/index', { title: 'Falcon — Audit & Inspection' });

Example Router Mounts

In the main index.js, each plugin router should be mounted as follows:

// ── Plugins (Routers) ───────────────────────────────────────────── var lynx = require('./plugins/lynx'); app.use('/', lynx); var fraternate = require('./plugins/fraternate'); app.use('/', fraternate); var heavylifting = require('./plugins/heavylifting'); app.use('/', heavylifting); var cleaner_wrasse = require('./plugins/cleaner-wrasse'); app.use('/', cleaner_wrasse); var semini = require('./plugins/semini'); app.use('/', semini); var heron = require('./plugins/heron'); app.use('/', heron); const falcon = require('./plugins/falcon'); app.use('/falcon', falcon); // ✅ Mounted under /falcon, views in plugins/falcon/views/falcon/ const atlas = require('./plugins/atlas'); app.use('/atlas', atlas); // ✅ Mounted under /atlas, views in plugins/atlas/views/atlas/ 

Incorrect Export Pattern

Do not use an alternate export style that returns multiple values, such as:

// ------------------------------------------------------------------- // Incorrect pattern // ------------------------------------------------------------------- module.exports = { manifest, createRouter, init, shutdown, defaultConfig, }; 

Summary

✅ Each plugin must:

  • Export a single router instance via module.exports
  • Contain namespaced Handlebars views in plugins/<plugin>/views/<plugin>/
  • Register partials under a namespace matching the plugin name (e.g. falcon/, atlas/)
  • Be mounted in index.js under /<plugin> using app.use()

This ensures that all plugin routes, templates, and partials remain isolated and predictable while maintaining full compatibility with the shared Express-Handlebars configuration.

modal1
modal2
modal3
docs_javascript
new_issue_button.handlebars
shortcut_edit