Action functions let you handle changes like form submissions on the server. They help update data safely and keep your app interactive.
0
0
Action functions for mutations in Remix
Introduction
When a user submits a form to add or update information.
When you want to change data in a database after a button click.
When handling user input that changes app state on the server.
When you need to process POST requests in Remix routes.
When you want to keep UI and data in sync after user actions.
Syntax
Remix
import { redirect } from '@remix-run/node'; export async function action({ request }) { const formData = await request.formData(); // process formData and perform mutation return redirect('/some-path'); }
The action function runs on the server when a form is submitted.
You get the request object to read form data or JSON.
Examples
Handles a form with a 'name' field and redirects after saving.
Remix
import { redirect } from '@remix-run/node'; export async function action({ request }) { const formData = await request.formData(); const name = formData.get('name'); // save name to database return redirect('/thank-you'); }
Handles JSON data sent via fetch and returns a JSON response.
Remix
import { json } from '@remix-run/node'; export async function action({ request }) { const data = await request.json(); // update database with JSON data return json({ success: true }); }
Sample Program
This example shows a simple contact form. When submitted, the action function reads the message, logs it, and redirects the user to a thank-you page.
Remix
import { redirect } from '@remix-run/node'; export async function action({ request }) { const formData = await request.formData(); const message = formData.get('message'); // Imagine saving message to a database here console.log('Received message:', message); return redirect('/thank-you'); } export default function Contact() { return ( <form method="post" aria-label="Contact form"> <label htmlFor="message">Message:</label> <textarea id="message" name="message" required></textarea> <button type="submit">Send</button> </form> ); }
OutputSuccess
Important Notes
Action functions only run on the server, so you can safely handle secrets and database updates.
Always return a response like redirect() or json() to tell Remix what to do next.
Use method="post" on your form to trigger the action function.
Summary
Action functions handle form submissions and data changes on the server.
They receive the request and let you read form or JSON data.
Return a redirect or JSON response to control what happens after mutation.