How to Send JSON Response in Oak Framework for Deno
In Oak for Deno, send a JSON response by setting
ctx.response.body to a JavaScript object. Oak automatically converts it to JSON and sets the correct Content-Type header.Syntax
To send a JSON response in Oak, assign a JavaScript object or array to ctx.response.body. Oak handles serialization and headers automatically.
Parts explained:
ctx: The context object representing the HTTP request and response.response: The response part of the context.body: The property where you set the response content.
typescript
ctx.response.body = { message: "Hello, world!" };Example
This example shows a simple Oak server that responds with JSON when you visit the root URL.
typescript
import { Application, Router } from "https://deno.land/x/oak@v12.5.0/mod.ts"; const router = new Router(); router.get("/", (ctx) => { ctx.response.body = { greeting: "Hello from Oak!" }; }); const app = new Application(); app.use(router.routes()); app.use(router.allowedMethods()); console.log("Server running on http://localhost:8000"); await app.listen({ port: 8000 });
Output
Server running on http://localhost:8000
Common Pitfalls
Some common mistakes when sending JSON responses in Oak include:
- Setting
ctx.response.bodyto a stringified JSON instead of an object, which causes Oak to send plain text instead of JSON. - Not setting the response body at all, resulting in empty responses.
- Manually setting
Content-Typeheader incorrectly; Oak sets it automatically when you assign an object.
typescript
/* Wrong way: sending string instead of object */ ctx.response.body = JSON.stringify({ error: "Not found" }); ctx.response.type = "application/json"; // manual header /* Right way: assign object directly */ ctx.response.body = { error: "Not found" };
Quick Reference
Summary tips for sending JSON in Oak:
- Assign JavaScript objects or arrays directly to
ctx.response.body. - Do not stringify the object yourself.
- Oak sets
Content-Type: application/jsonautomatically. - Use
ctx.response.statusto set HTTP status codes if needed.
Key Takeaways
Set ctx.response.body to a JavaScript object to send JSON in Oak.
Do not manually stringify JSON; Oak handles it automatically.
Oak sets the Content-Type header to application/json when body is an object.
Use ctx.response.status to control HTTP status codes with JSON responses.