{"id":17743,"library":"koa-ejs","title":"Koa EJS View Rendering Middleware","description":"Koa-ejs is a middleware for the Koa.js framework that facilitates server-side rendering using the EJS templating engine. It provides seamless integration with Koa's context (`ctx.render`) to render EJS templates, supporting all features of the underlying EJS library, including layouts, partials (includes), and access to `ctx.state` for passing data to views. The current stable version is 5.1.0, and the project appears actively maintained with recent releases addressing bug fixes and EJS v3 compatibility. Its primary differentiator is its tight integration with the Koa ecosystem, offering a straightforward setup for server-rendered applications, making it a popular choice for traditional web server setups with Koa. The release cadence is somewhat infrequent but significant updates (like v5.0.0) introduce major changes and compatibility improvements.","status":"active","version":"4.3.0","language":"javascript","source_language":"en","source_url":"git://github.com/koajs/ejs","tags":["javascript","koa","render","ejs","view"],"install":[{"cmd":"npm install koa-ejs","lang":"bash","label":"npm"},{"cmd":"yarn add koa-ejs","lang":"bash","label":"yarn"},{"cmd":"pnpm add koa-ejs","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Runtime dependency for the EJS templating engine. Version 5.x of koa-ejs requires ejs v3.","package":"ejs","optional":false},{"reason":"Peer dependency as it functions as a Koa middleware.","package":"koa","optional":false}],"imports":[{"note":"The `koa-ejs` package exports its main rendering function as a default export. For ESM, use default import. For CommonJS, `require('koa-ejs')` directly returns the render function.","wrong":"const render = require('koa-ejs'); // CommonJS syntax\nimport { render } from 'koa-ejs'; // Incorrect named import, it's a default export","symbol":"render","correct":"import render from 'koa-ejs';"},{"note":"Standard Koa import. Koa is typically imported as a default export in ESM environments.","wrong":"const Koa = require('koa');","symbol":"Koa","correct":"import Koa from 'koa';"},{"note":"Node.js built-in module for path manipulation. For ESM, use `import path from 'path';`.","wrong":"const path = require('path');","symbol":"path","correct":"import path from 'path';"}],"quickstart":{"code":"import Koa from 'koa';\nimport render from 'koa-ejs';\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nimport { dirname } from 'path';\n\nconst __filename = fileURLToP<ctrl60>ath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nconst app = new Koa();\n\n// Configure EJS rendering\nrender(app, {\n  root: path.join(__dirname, 'view'),\n  layout: 'template', // Name of your layout file (e.g., template.html)\n  viewExt: 'html',\n  cache: process.env.NODE_ENV === 'production', // Cache templates in production\n  debug: process.env.NODE_ENV !== 'production' // Debug mode in development\n});\n\n// Example route to render a view\napp.use(async (ctx) => {\n  const user = { name: 'Alice', age: 30 };\n  // Add data to ctx.state to be accessible in templates\n  ctx.state.title = 'User Profile';\n  ctx.state.user = user;\n\n  // Render 'user.html' template with layout 'template.html'\n  await ctx.render('user', { message: 'Welcome back!' });\n});\n\nconst port = process.env.PORT || 7001;\napp.listen(port, () => {\n  console.log(`Server running on http://localhost:${port}`);\n});\n\n// --- Create 'view' directory and 'user.html', 'template.html' files ---\n// (Ensure you create these files in a 'view' folder next to your main script)\n\n// Example content for view/user.html:\n// <h1><%= title %></h1>\n// <p>Hello, <%= user.name %>! You are <%= user.age %> years old.</p>\n// <p><%= message %></p>\n\n// Example content for view/template.html:\n// <!DOCTYPE html>\n// <html>\n// <head>\n//   <title><%= title %></title>\n// </head>\n// <body>\n//   <h3>Header from layout</h3>\n//   <%- body %>\n//   <h4>Footer from layout</h4>\n// </body>\n// </html>","lang":"typescript","description":"This quickstart demonstrates how to set up `koa-ejs` middleware for an ESM Koa application, configure view paths, enable/disable caching based on environment, handle `ctx.state` for global data, and render a template with a layout. It includes minimal example template content to make the code runnable and illustrate the basic functionality."},"warnings":[{"fix":"Review EJS v3 migration guides for any breaking changes in template syntax or options (e.g., custom delimiters). Test existing templates thoroughly after upgrading to `koa-ejs` v5+.","message":"Version 5.0.0 of `koa-ejs` introduced significant changes, including an update to support EJS v3. Ensure your EJS templates and configurations are compatible with EJS v3 when upgrading to `koa-ejs` v5 or later. This might involve minor adjustments to template syntax or options if you were using older EJS versions.","severity":"breaking","affected_versions":">=5.0.0"},{"fix":"For development, set `cache: false` in the `render()` options. For production, ensure `cache: true` or rely on the default behavior. A common pattern is `cache: process.env.NODE_ENV === 'production'`.","message":"The default value for the `cache` option in `koa-ejs` is `true`. While convenient for development, explicitly setting `cache: false` is often necessary during development to see template changes without restarting the server. In production, always ensure caching is enabled for optimal performance.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Continue to install and import the package as `koa-ejs`. If you encounter `@koa/ejs` in other contexts, be aware it might refer to an alternative or deprecated package that is not actively maintained by the `koajs` organization.","message":"The `v5.0.0` release notes mentioned 'rename package to @koa/ejs'. However, the `koa-ejs` package on npm still retains its original name and continues to be updated under `koa-ejs`. This can cause confusion regarding which package to install or import. The `koa-ejs` package is the canonical one for this project.","severity":"gotcha","affected_versions":">=5.0.0"},{"fix":"For new projects or when modernizing, use ESM imports (`import render from 'koa-ejs';`) and configure your project for ESM (e.g., `\"type\": \"module\"` in `package.json` and updating `__dirname` resolution for file paths).","message":"The `README` examples often use `require()` for imports, which is a CommonJS pattern. While still supported by Node.js, modern Koa applications increasingly adopt ESM. Mixing CJS and ESM can lead to module resolution issues or require specific configurations.","severity":"deprecated","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-23T00:00:00.000Z","next_check":"2026-07-22T00:00:00.000Z","problems":[{"fix":"Ensure the `root` option in `render()` points to the correct directory containing your EJS files. Verify the filename passed to `ctx.render()` (e.g., `user` for `user.html`) and that `viewExt` is correctly configured (default is 'html'). Check for typos in filenames and paths.","cause":"The template file specified in `ctx.render()` was not found in the configured `root` directory, or it has an incorrect file extension.","error":"Error: Failed to lookup view \"<template_name>\" in views directory \"<path_to_root>\""},{"fix":"Ensure all variables required by your EJS template are available either in `ctx.state` (e.g., `ctx.state.title = 'My Page';`) or as an object passed as the second argument to `await ctx.render('template', { variableName: value });`. Double-check variable names for exact matches.","cause":"A variable used within your EJS template was not passed as data to `ctx.render()` or made available through `ctx.state` before rendering. This often happens due to typos or forgetting to include a variable.","error":"ReferenceError: <variable_name> is not defined"},{"fix":"Run `npm install koa-ejs` or `yarn add koa-ejs` in your project's root directory to install the package. If already installed, check your `node_modules` directory and ensure proper module resolution (e.g., for monorepos or when using custom module loaders).","cause":"The `koa-ejs` package is not installed in your project, or Node.js cannot resolve its path. This can occur after cloning a repository or due to issues with `node_modules`.","error":"Error: Cannot find module 'koa-ejs'"}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null}