{"id":16854,"library":"method-override","title":"HTTP Method Override Middleware","description":"method-override is a Node.js middleware designed for Express.js and similar frameworks, enabling clients to utilize HTTP verbs like PUT or DELETE even when their environment (e.g., older browsers, specific `XMLHttpRequest` implementations) primarily supports GET and POST. It achieves this by inspecting a specified request header (e.g., `X-HTTP-Method-Override`), a query string parameter (e.g., `_method`), or a custom function's return value to override the `req.method` property. The current stable version is 3.0.0. The package has a stable, but not high-frequency, release cadence, primarily focusing on maintaining compatibility within the Express.js ecosystem, updating dependencies, and adjusting Node.js version support. Its key differentiator lies in its flexibility in defining the 'getter' for the overridden method and its explicit warning about middleware order for security and functionality, positioning it as a robust solution for method simulation in web applications.","status":"active","version":"3.0.0","language":"javascript","source_language":"en","source_url":"https://github.com/expressjs/method-override","tags":["javascript"],"install":[{"cmd":"npm install method-override","lang":"bash","label":"npm"},{"cmd":"yarn add method-override","lang":"bash","label":"yarn"},{"cmd":"pnpm add method-override","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Used for internal debugging and logging within the middleware, affecting verbose output.","package":"debug","optional":false}],"imports":[{"note":"While typically used with CommonJS `require`, modern Node.js environments and build tools may prefer ESM `import`. The package primarily exports a default function.","wrong":"const methodOverride = require('method-override').default;","symbol":"methodOverride","correct":"import methodOverride from 'method-override';"},{"note":"This is the standard CommonJS import for Node.js applications, which returns the middleware function directly. It's not a named export.","wrong":"import { methodOverride } from 'method-override';","symbol":"methodOverride","correct":"const methodOverride = require('method-override');"},{"note":"The `methodOverride` function must be invoked with a `getter` argument (string or function) to return the actual middleware function. Passing it directly without arguments will lead to an error or incorrect behavior.","wrong":"app.use(methodOverride);","symbol":"methodOverride","correct":"app.use(methodOverride('X-HTTP-Method-Override'));"}],"quickstart":{"code":"import express from 'express';\nimport methodOverride from 'method-override';\n\nconst app = express();\nconst port = 3000;\n\n// --- Configuration of method-override middleware ---\n// Option 1: Override using the 'X-HTTP-Method-Override' header\napp.use(methodOverride('X-HTTP-Method-Override'));\n\n// Option 2: Override using a query string parameter named '_method'\n// This allows clients to send POST requests with ?_method=PUT or ?_method=DELETE\napp.use(methodOverride('_method'));\n\n// Option 3: Custom getter function (e.g., from a form field)\napp.use(methodOverride(function (req, res) {\n  if (req.body && typeof req.body === 'object' && '_method' in req.body) {\n    // look in urlencoded POST bodies and delete it\n    const method = req.body._method;\n    delete req.body._method;\n    return method;\n  }\n}));\n\n// Ensure method-override is used before any routes or other middleware\n// that rely on the correct HTTP method (e.g., csurf, route handlers).\n\n// --- Example Routes ---\napp.get('/', (req, res) => {\n  res.send(`\n    <h1>Method Override Example</h1>\n    <p>Original Method: ${req.originalMethod}</p>\n    <p>Current Method: ${req.method}</p>\n    <form action=\"/resource?_method=DELETE\" method=\"POST\">\n      <button type=\"submit\">Delete via Query String</button>\n    </form>\n    <p>Try sending a POST request with 'X-HTTP-Method-Override: PUT' header to /resource.</p>\n  `);\n});\n\napp.all('/resource', (req, res) => {\n  const message = `Received a ${req.method} request to /resource (original: ${req.originalMethod || req.method})`;\n  console.log(message);\n  res.status(200).send(message);\n});\n\napp.listen(port, () => {\n  console.log(`Server listening at http://localhost:${port}`);\n  console.log('Test with curl:');\n  console.log('  curl -X POST -H \"X-HTTP-Method-Override: PUT\" http://localhost:3000/resource');\n  console.log('  curl -X POST \"http://localhost:3000/resource?_method=DELETE\"');\n});","lang":"javascript","description":"Demonstrates setting up `method-override` middleware in an Express application to allow HTTP method overriding via a custom header or a query string parameter, showing how to send requests that utilize these overrides via an HTML form and curl examples."},"warnings":[{"fix":"Upgrade your Node.js environment to a currently supported LTS version (e.g., Node.js 16 or newer) to ensure compatibility and receive security updates.","message":"Version 3.0.0 of method-override dropped support for Node.js versions below 0.10. While highly unlikely to affect modern applications, ensure your Node.js runtime meets this minimal requirement if upgrading from very old versions.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Always place `app.use(methodOverride(...))` at the beginning of your middleware chain, typically right after `express.json()` and `express.urlencoded()` if they are used, but before session management, CSRF protection, or routing definitions.","message":"It is critical that `method-override` middleware is mounted *before* any other middleware or route handlers that need to know the correct HTTP method of the request. Placing it after could lead to security vulnerabilities (e.g., CSRF protection not working correctly) or incorrect routing decisions.","severity":"gotcha","affected_versions":">=1.0.0"},{"fix":"Avoid setting `options.methods` to `null` or including methods other than `POST` unless you fully understand the security implications and have mitigated potential risks. For most use cases, the default `['POST']` is appropriate and safer.","message":"The `options.methods` parameter defaults to `['POST']`, meaning method overriding is only checked if the original request method was POST. Changing this to allow `null` (all methods) or other methods can introduce security issues, especially when requests pass through caches, as it can lead to unexpected behavior or cache poisoning.","severity":"gotcha","affected_versions":">=1.0.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Ensure you call the `methodOverride` function with its required `getter` argument (e.g., a string for a header/query param or a custom function) to get the actual middleware function to pass to `app.use`.","cause":"Attempting to use `methodOverride` as middleware without invoking it first, e.g., `app.use(methodOverride);` instead of `app.use(methodOverride('X-HTTP-Method-Override'));`.","error":"TypeError: methodOverride is not a function"},{"fix":"For ESM projects, use `import methodOverride from 'method-override';`. If you must use `require` in an ESM file, consider dynamic import `const methodOverride = await import('method-override');` or ensure your environment supports CommonJS `require` calls.","cause":"Attempting to use `require('method-override')` in an ECMAScript Module (ESM) context without proper configuration (e.g., in a file with `\"type\": \"module\"` in `package.json` or a `.mjs` file).","error":"ReferenceError: require is not defined"},{"fix":"1. Verify `method-override` is at the very top of your `app.use` calls. 2. Double-check the exact header name or query parameter key used in the client request matches the `getter` argument. 3. Ensure the original request from the client is a `POST` request, as this is the default and safest method for overrides.","cause":"This can be due to several reasons: `method-override` middleware being placed too late in the middleware chain; the specified `getter` (header name, query parameter) not matching the client's request; or the original request method not being `POST` when `options.methods` is at its default.","error":"The HTTP method is not being overridden as expected."}],"ecosystem":"npm","meta_description":null}