Writing plugins

The plugin system in Dotpress is designed to extend application features and promote code reusability across projects, while keeping the core library lightweight and focused.

A plugin is simply a function that receives a PluginAPI and can:

  • inject routes or route groups
  • register global middlewares
  • attach lifecycle hooks
  • register response filters

For example, let's say you need to create an authentication plugin. This plugin will have to expose routes to get access tokens and to attach a global middleware to parse token and attach a user to the context.

import type { Plugin } from 'dotpress';

export const configureAuthPlugin = (options: YourPluginOptions): Plugin => {
  // Configure here your required services: data provider, token service, etc.

  return (api) => {
    // Define a route to authenticate a user and return access token
    api.addRoute({
      method: 'post',
      path: '/auth/access-token',
      schema: (z) => ({
        body: z.object({
          username: z.string(),
          password: z.number().optional(),
        }),
        response: z.object({
          accessToken: z.string()
        })
      }),
      handler: async ({ req }) => {
        // Do something here ...

        return {
          accessToken: '... your token ...'
        }
      }
    })

    api.addRoute({
      method: 'post',
      path: '/auth/refresh-token',
      handler: async ({ req }) => {
        // Handle token refresh here ...
      }
    })

    api.addGlobalMiddleware(async (ctx) => {
      // Parse access token from headers
      // Then, if a valid token is provided:
      // Attach current user to request context
    }
  }
}

Usage in your application

import { createApp } from 'dotpress'
import { configureAuthPlugin } from './plugins/auth.ts'

const authPlugin = configureAuthPlugin({
  // ... pass here required configuration options
})

const app = await createApp({
  plugins: [authPlugin]
})