Introducing Next.js 13 API Routes
Next.js, a popular React framework for building web applications, has just released version 13 with a new feature called API Routes. This new feature allows developers to easily create and deploy serverless API endpoints within their Next.js applications.
What are API Routes?
API Routes in Next.js 13 provide a way for developers to define server-side logic for handling HTTP requests. This can be used to create custom API endpoints for fetching and updating data, handling authentication, and more. API Routes are built using the same familiar Next.js file-based routing system, which makes it easy to organize and maintain API logic alongside the rest of the application code.
How to use API Routes
To create an API Route in Next.js 13, simply create a new file in the api
directory within your Next.js project. This file should export a function that handles the incoming HTTP request and returns a response. Here’s an example of a simple API Route that returns a list of products:
import products from './data/products' export default function handler(req, res) { res.status(200).json(products) }
Once you’ve defined your API Route, Next.js will automatically set up the necessary serverless functions to handle incoming requests. You can then use these API endpoints in your client-side code, just like any other HTTP API.
Benefits of API Routes
API Routes in Next.js 13 offer several benefits for developers. First, they provide a seamless way to integrate server-side logic into your Next.js application without the need for a separate backend server. This simplifies the development process and reduces infrastructure overhead. Additionally, API Routes are automatically optimized for performance and scalability, thanks to Next.js’s built-in serverless architecture.
Getting Started with Next.js 13
If you’re ready to try out Next.js 13 and its new API Routes feature, you can get started by installing the latest version of Next.js using npm:
npm install next@latest
Once you’ve upgraded to Next.js 13, you can start creating API Routes in your existing Next.js applications or use them in new projects. The Next.js documentation provides detailed guidance on how to use API Routes, along with best practices for building serverless APIs with Next.js.
Conclusion
Next.js 13’s new API Routes feature is an exciting addition that further enhances the capabilities of the popular React framework. With API Routes, developers can easily create and deploy serverless API endpoints within their Next.js applications, without the need for a separate backend server. This opens up new possibilities for building powerful, integrated web applications with Next.js.
when will we use this? import { NextResponse } from 'next/server'
loveeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
Hey, thanks for the video, btw any ideas how to fix this error with TS? TS2339: Property 'json' does not exist on type '{ new (body?: BodyInit | null | undefined, init?: ResponseInit | undefined): Response; prototype: Response; error(): Response; redirect(url: string | URL, status?: number | undefined): Response; }'.
Can not find any tutorial with real-life app like blog with complete CRUD functionality with these route handlers, apis, etc. Would be very helpful. Thank You!
it is more easier than before ,
I tried to upload file , i thought it its standard web api to use formData ,
but i think the api route handlers parse data or change it :
import { Directus } from '@directus/sdk';
import { NextResponse } from 'next/server';
export async function POST(request: Request) {
const formData = await request.formData();
const file = formData.get('file');
formData.append('folder', '887b5198-6b28-4289-8117-87deb4df5e71');
formData.append('file', file as File);
console.log("form data", formData);
const token: string = process.env.DIRECTUS_JOB_TOKEN!;
const url: string = process.env.DIRECTUS_URL!;
const directus = new Directus<any>(url);
await directus.auth.static(token);
const fileResponse = await directus.files.createOne(formData);
return NextResponse.json({ "message": "File Uploaded" });
}
the Axios error :
[AxiosError: Data after transformation must be a string, an ArrayBuffer, a Buffer, or a Stream]
even if i tried this on client side it works fine :
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const form = new FormData(event.currentTarget);
console.log(form)
// this using api route handler
// const response = await fetch('/api/job', {
// method: 'POST',
// body: form,
// })
// console.log(response)
const directus = new Directus<any>('https://example.com/'😉;
await directus.auth.static('secretkeys');
form.append('folder', '887b5198-6b28-4289-8117-87deb4df5e71');
const file = form.get('file');
if (file instanceof Blob) {
form.append('file', file);
} else {
throw new Error('Invalid file data');
}
const fileRes = directus.files.createOne(form)
.then(async (Response) => {
return await Response?.data.id;
})
.catch(error => {
console.error(error);
});
console.log(fileRes)
};
why is that ? is api route handlers parsing or changing the formData ?
Thank you Tuomo! Helped me a lot 🙂
Will route handlers work with next auth?
Well done. And, easy to follow
how get req.body on post method ?
I've trouble with POST method, when I using POST handler I cannot retrieve the req.body.Is there any solution for next js 13?, I found bodyparser stuff but I don't know where to put it in.
I am waiting for next video sir ?
can you please make a video for implementing next-auth in app/api which was previously in pages/api, thanks
already implemented in my website. the metadata api is very helpful 👍
Hello appreciate this, but is there a way to actually read body data when doing a Post request ?(request.body is just a readable stream and can't be used to get useful data)
This is so powerful
great video mate, would love to see more of these.
Hey, great video. Any idea how we can implement NextAuth with route handlers now?
pls, how use Response to do a res.revalidate('/')
This is an awesome Next 13.2 api route tutorial, simple and clear explanation, easy to follow, please dive deeper, thank you 🤩
Thanks for the updated info!