How can I use route handler in app router
Answered
Mossyrose gall wasp posted this in #help-forum
Mossyrose gall waspOP
Hello, im currently switch my pages router to app router but i faced some issues about api routes. Here is my pages/api/image.ts code:
I want to move this code new app router's app/api/image/route.ts.
Any help really appreciated
import { Canvas } from '@napi-rs/canvas';
import { NextApiRequest, NextApiResponse } from 'next';
const createOgp = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
const { color } = req.query;
const canvas = new Canvas(WIDTH, HEIGHT);
const ctx = canvas.getContext('2d');
ctx.fillStyle = `#${color}`;
ctx.fillRect(0, 0, 1000, 1000);
const buffer = await canvas.encode('jpeg');
res.writeHead(200, {
'Content-Type': 'image/jpeg',
'Content-Length': buffer.length
});
res.end(buffer, 'binary');
};
export default createOgp;I want to move this code new app router's app/api/image/route.ts.
Any help really appreciated
Answered by B33fb0n3
You can use the definitions from the docs and then add your code afterwards: https://nextjs.org/docs/app/building-your-application/routing/route-handlers#convention
3 Replies
@Mossyrose gall wasp Hello, im currently switch my pages router to app router but i faced some issues about api routes. Here is my pages/api/image.ts code:
ts
import { Canvas } from '@napi-rs/canvas';
import { NextApiRequest, NextApiResponse } from 'next';
const createOgp = async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
const { color } = req.query;
const canvas = new Canvas(WIDTH, HEIGHT);
const ctx = canvas.getContext('2d');
ctx.fillStyle = `#${color}`;
ctx.fillRect(0, 0, 1000, 1000);
const buffer = await canvas.encode('jpeg');
res.writeHead(200, {
'Content-Type': 'image/jpeg',
'Content-Length': buffer.length
});
res.end(buffer, 'binary');
};
export default createOgp;
I want to move this code new app router's app/api/image/route.ts.
Any help really appreciated
You can use the definitions from the docs and then add your code afterwards: https://nextjs.org/docs/app/building-your-application/routing/route-handlers#convention
Answer
Mossyrose gall waspOP
thank you so much @B33fb0n3 😄