CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-nuxt--kit

Toolkit for authoring modules and interacting with Nuxt

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

server-integration.mddocs/

Server Integration

Nitro server handler management, plugin registration, and server-side functionality integration for Nuxt applications.

Capabilities

Server Handler Management

Add and manage server-side request handlers for API routes and middleware.

/**
 * Add Nitro server handler
 * @param handler - Server handler configuration
 */
function addServerHandler(handler: NitroEventHandler): void;

/**
 * Add development-only server handler
 * @param handler - Development server handler configuration
 */
function addDevServerHandler(handler: NitroDevEventHandler): void;

interface NitroEventHandler {
  /** Handler route pattern */
  route?: string;
  /** HTTP method(s) */
  method?: HTTPMethod | HTTPMethod[];
  /** Handler function file path */
  handler: string;
  /** Lazy load handler */
  lazy?: boolean;
  /** Handler middleware flag */
  middleware?: boolean;
  /** Handler metadata */
  meta?: HandlerMeta;
}

interface NitroDevEventHandler extends NitroEventHandler {
  /** Development environment only */
  dev?: boolean;
}

type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";

interface HandlerMeta {
  /** Handler name */
  name?: string;
  /** Handler description */
  description?: string;
  [key: string]: any;
}

Usage Examples:

import { addServerHandler, addDevServerHandler } from "@nuxt/kit";

// Add API route handler
addServerHandler({
  route: "/api/users",
  handler: "~/server/api/users.get.ts"
});

// Add handler with specific method
addServerHandler({
  route: "/api/auth/login",
  method: "POST",
  handler: "~/server/api/auth/login.post.ts"
});

// Add middleware handler
addServerHandler({
  handler: "~/server/middleware/cors.ts",
  middleware: true
});

// Add lazy-loaded handler
addServerHandler({
  route: "/api/heavy-computation",
  handler: "~/server/api/heavy.ts",
  lazy: true
});

// Development-only handler
addDevServerHandler({
  route: "/api/dev/debug",
  handler: "~/server/api/debug.ts",
  method: "GET"
});

Server Plugin System

Register server-side plugins for Nitro initialization and middleware.

/**
 * Add Nitro server plugin
 * @param plugin - Plugin file path
 */
function addServerPlugin(plugin: string): void;

Usage Examples:

import { addServerPlugin } from "@nuxt/kit";

// Add server initialization plugin
addServerPlugin("~/server/plugins/database.ts");

// Add authentication plugin
addServerPlugin("~/server/plugins/auth-setup.ts");

// Module adding server plugin
export default defineNuxtModule({
  setup() {
    addServerPlugin(resolve(runtimeDir, "server/plugin.mjs"));
  }
});

Nitro Instance Access

Access the Nitro server instance for advanced server configuration.

/**
 * Access Nitro instance (only available after 'ready' hook)
 * @returns Nitro server instance
 * @throws Error if called before Nitro is ready
 */
function useNitro(): Nitro;

interface Nitro {
  /** Nitro options */
  options: NitroOptions;
  /** Storage layer */
  storage: Storage;
  /** Server hooks */
  hooks: Hookable;
}

Usage Examples:

import { useNitro } from "@nuxt/kit";

export default defineNuxtModule({
  setup(options, nuxt) {
    // Wait for Nitro to be ready
    nuxt.hook("ready", async () => {
      const nitro = useNitro();
      
      // Access Nitro configuration
      console.log("Nitro preset:", nitro.options.preset);
      
      // Configure storage
      nitro.storage.setDriver("custom", customStorageDriver);
      
      // Add Nitro hooks
      nitro.hooks.hook("render:response", (response) => {
        response.headers["X-Custom-Header"] = "value";
      });
    });
  }
});

Prerendering Support

Configure routes for static generation and prerendering.

/**
 * Add routes to be prerendered
 * @param routes - Route path(s) to prerender
 */
function addPrerenderRoutes(routes: string | string[]): void;

Usage Examples:

import { addPrerenderRoutes } from "@nuxt/kit";

// Add static routes for prerendering
addPrerenderRoutes([
  "/about",
  "/contact",
  "/privacy-policy"
]);

// Dynamic route prerendering
export default defineNuxtModule({
  async setup() {
    // Fetch dynamic routes
    const posts = await fetchBlogPosts();
    const routes = posts.map(post => `/blog/${post.slug}`);
    
    addPrerenderRoutes(routes);
  }
});

// Conditional prerendering
if (process.env.PRERENDER_BLOG === "true") {
  addPrerenderRoutes("/blog/**");
}

Server-Side Auto-Imports

Configure auto-imports specifically for server-side code.

/**
 * Add server-side auto-imports for Nitro
 * @param imports - Import or array of imports to register
 */
function addServerImports(imports: Import | Import[]): void;

/**
 * Add directories to be scanned for server auto-imports
 * @param dirs - Directory path(s) to scan
 * @param opts - Directory scanning options
 */
function addServerImportsDir(
  dirs: string | string[],
  opts?: { prepend?: boolean }
): void;

/**
 * Add directories to be scanned by Nitro like ~/server
 * @param dirs - Directory path(s) to scan
 * @param opts - Directory scanning options
 */
function addServerScanDir(
  dirs: string | string[],
  opts?: { prepend?: boolean }
): void;

Usage Examples:

import { 
  addServerImports, 
  addServerImportsDir, 
  addServerScanDir 
} from "@nuxt/kit";

// Add server utility imports
addServerImports([
  { name: "validateRequest", from: "~/server/utils/validation" },
  { name: "useDatabase", from: "~/server/utils/database" }
]);

// Add server utils directory
addServerImportsDir("~/server/utils");

// Add custom server directories for scanning
addServerScanDir([
  "~/server/custom-api",
  "~/server/custom-middleware"
]);

Advanced Nitro Configuration

Configure Nitro server options and behavior through modules.

Server Handler Patterns:

import { addServerHandler } from "@nuxt/kit";

export default defineNuxtModule({
  setup(options) {
    // RESTful API handlers
    addServerHandler({
      route: "/api/users/:id",
      method: "GET",
      handler: "~/server/api/users/[id].get.ts"
    });
    
    addServerHandler({
      route: "/api/users/:id",
      method: "PUT",
      handler: "~/server/api/users/[id].put.ts"
    });
    
    // Catch-all handler
    addServerHandler({
      route: "/api/proxy/**",
      handler: "~/server/api/proxy.ts"
    });
    
    // WebSocket handler (if supported)
    addServerHandler({
      route: "/api/ws",
      handler: "~/server/api/websocket.ts"
    });
  }
});

Server Plugin Integration:

import { addServerPlugin, createResolver } from "@nuxt/kit";

export default defineNuxtModule({
  setup() {
    const resolver = createResolver(import.meta.url);
    
    // Add server initialization
    addServerPlugin(resolver.resolve("./runtime/server/init.mjs"));
    
    // Add database connection
    addServerPlugin(resolver.resolve("./runtime/server/database.mjs"));
  }
});

Nitro Hook Integration:

export default defineNuxtModule({
  setup(options, nuxt) {
    // Configure Nitro through Nuxt hooks
    nuxt.hook('nitro:config', (nitroConfig) => {
      nitroConfig.plugins = nitroConfig.plugins || [];
      nitroConfig.plugins.push("~/server/plugins/custom.ts");
      
      // Add custom Nitro configuration
      nitroConfig.experimental = {
        ...nitroConfig.experimental,
        wasm: true
      };
    });
    
    // Add Nitro build hooks
    nuxt.hook('nitro:build:before', (nitro) => {
      console.log('Nitro build starting...');
    });
  }
});

Server Storage Configuration:

export default defineNuxtModule({
  setup(options, nuxt) {
    nuxt.hook('nitro:config', (nitroConfig) => {
      // Configure Redis storage
      nitroConfig.storage = nitroConfig.storage || {};
      nitroConfig.storage.redis = {
        driver: 'redis',
        host: process.env.REDIS_HOST,
        port: process.env.REDIS_PORT,
        password: process.env.REDIS_PASSWORD
      };
      
      // Configure file system storage
      nitroConfig.storage.fs = {
        driver: 'fs',
        base: './data'
      };
    });
  }
});

Types

interface NitroOptions {
  /** Deployment preset */
  preset?: string;
  /** Server handlers */
  handlers?: NitroEventHandler[];
  /** Server plugins */
  plugins?: string[];
  /** Storage configuration */
  storage?: Record<string, any>;
  /** Experimental features */
  experimental?: Record<string, any>;
  [key: string]: any;
}

interface Storage {
  /** Set storage driver */
  setDriver(name: string, driver: any): void;
  /** Get item from storage */
  getItem(key: string): Promise<any>;
  /** Set item in storage */
  setItem(key: string, value: any): Promise<void>;
  /** Remove item from storage */
  removeItem(key: string): Promise<void>;
  [key: string]: any;
}

interface Hookable {
  /** Register hook */
  hook<T>(name: string, fn: T): () => void;
  /** Call hook */
  callHook<T>(name: string, ...args: any[]): Promise<T>;
}

Install with Tessl CLI

npx tessl i tessl/npm-nuxt--kit

docs

auto-imports.md

build-system.md

compatibility.md

components.md

configuration.md

context-runtime.md

development-tools.md

index.md

module-system.md

path-resolution.md

plugins-templates.md

server-integration.md

tile.json