How to Return JSON from Loader in Remix: Simple Guide
In Remix, return JSON from a loader by importing and using the
json() helper from @remix-run/node. Wrap your data inside json(data) and return it from the loader function to send a proper JSON response.Syntax
The loader function is an async function that fetches data for your route. To return JSON, import json from @remix-run/node and return json(yourData).
- loader: async function that runs on the server before rendering
- json(data): helper that formats data as a JSON response with correct headers
javascript
import { json } from '@remix-run/node'; export async function loader() { const data = { message: 'Hello from loader!' }; return json(data); }
Output
{"message":"Hello from loader!"}
Example
This example shows a loader returning JSON data and a React component using useLoaderData() to access it.
javascript
import { json } from '@remix-run/node'; import { useLoaderData } from '@remix-run/react'; export async function loader() { const user = { id: 1, name: 'Alice' }; return json(user); } export default function User() { const user = useLoaderData(); return ( <main> <h1>User Info</h1> <p>ID: {user.id}</p> <p>Name: {user.name}</p> </main> ); }
Output
<main>
<h1>User Info</h1>
<p>ID: 1</p>
<p>Name: Alice</p>
</main>
Common Pitfalls
- Not using the
json()helper and returning plain objects can cause errors or missing headers. - Returning raw data without
json()may send HTML instead of JSON. - Forgetting to import
jsonfrom@remix-run/nodeleads to runtime errors.
javascript
/* Wrong way: returning plain object */ export async function loader() { return { message: 'Hello' }; } /* Right way: using json() helper */ import { json } from '@remix-run/node'; export async function loader() { return json({ message: 'Hello' }); }
Quick Reference
- Import:
import { json } from '@remix-run/node' - Return JSON:
return json(data) - Access in component:
const data = useLoaderData()
Key Takeaways
Always use the json() helper from @remix-run/node to return JSON from loaders.
Loader functions run on the server and must return a Response or use json() for JSON data.
Access loader JSON data in components with useLoaderData() hook.
Avoid returning plain objects directly from loaders to prevent errors.
Import json explicitly to ensure proper JSON response formatting.