method-override-middleware Overview
The methodOverride middleware lets HTML forms submit PUT, PATCH, and DELETE requests by reading a hidden _method field from the form data. This enables RESTful routing without requiring JavaScript on the client.
Why Is This Needed?
HTML forms have a limitation: the <form> element's method attribute only accepts GET and POST. There is no method="DELETE" or method="PUT". This is a long-standing HTML specification constraint.
<!-- This works -->
<form method="post" action="/posts">...</form>
<!-- This does NOT work -- the browser treats it as GET -->
<form method="delete" action="/posts/42">...</form>This means if you want a "Delete" button that works without JavaScript, you have to route it through a POST and figure out what operation to perform some other way. That makes routing messy.
How Method Override Solves This
With method override, you add a hidden form field named _method that contains the real HTTP method:
<form method="post" action="/posts/42">
<input type="hidden" name="_method" value="DELETE" />
<button type="submit">Delete Post</button>
</form>The browser sends this as a normal POST. The methodOverride middleware reads the _method field, changes the request method from POST to DELETE, and removes the field from the form data. Your route handler sees a clean DELETE request.
This lets you use standard REST conventions:
| Action | Method | URL | Form |
|---|---|---|---|
| List posts | GET | /posts | Link or form with method="get" |
| Create post | POST | /posts | Form with method="post" |
| Update post | PUT | /posts/:id | Form with _method="PUT" |
| Delete post | DELETE | /posts/:id | Form with _method="DELETE" |
Quick Example
import { createRouter } from 'remix/fetch-router'
import { formData } from 'remix/form-data-middleware'
import { methodOverride } from 'remix/method-override-middleware'
let router = createRouter({
middleware: [
formData(),
methodOverride(),
],
})formData must come first
The methodOverride middleware reads from parsed form data. The formData middleware must appear before it in the middleware chain.
Next Steps
- Tutorial: Use RESTful Forms -- Step-by-step guide to creating delete and update forms.
- API Reference -- Complete documentation of options and behavior.