Setting Up Route Handlers in Your App

Marickian
By -
0
Setting Up Route Handlers in Your App

Setting Up Route Handlers in Your App

In this guide, we will walk through the setup for route handlers in your application. Follow these steps to create an API endpoint that handles HTTP requests.

Step 1: Create the API Directory

First, you need to create a special directory named API. This name is mandatory.

Step 2: Define the URL Segment

Inside the API directory, decide on a URL segment for your endpoint. For this example, we will use /tasks. This segment name is optional and can be customized.

Step 3: Create the Route File

Next, create a special file inside your chosen segment directory. Instead of naming it page.js, you should name it route.js. This file will contain the functions that handle different HTTP requests.

Step 4: Export Functions for HTTP Methods

From the route.js file, export functions that correspond to the HTTP methods you want to handle. Here are some common methods:

  • GET: The default HTTP method used by browsers to retrieve resources from the server.
  • POST: Used to add new resources to the server.
  • PUT: Used to update existing resources.
  • DELETE: Used to delete resources.

Each exported function will respond to its respective HTTP request.

Step 5: Example - Handling a GET Request

Let's create a function to handle a GET request. This function will retrieve tasks from the database.

import { db } from '../utils/db';

export async function GET(request) {
    const tasks = await db.task.findMany();
    return new Response(JSON.stringify({ data: tasks }), {
        headers: { 'Content-Type': 'application/json' },
    });
}

This function fetches all tasks from the database and returns them as a JSON response.

Step 6: Testing the GET Request

You can test the GET request directly in your browser or using tools like Thunder Client. Here’s how to do it:

  1. Open your browser and navigate to http://your-domain.com/api/tasks. You should see a list of tasks returned as JSON.
  2. In Thunder Client, create a new request with the same URL, set the method to GET, and send the request. You should receive the same JSON response.

By default, browsers perform a GET request, so this setup allows you to quickly test and retrieve data.

Step 7: Communicating with the Database

One of the advantages of route handlers is the ability to interact with your database. Here’s how you can fetch tasks from the database using Prisma:

import { db } from '../utils/db';

export async function GET(request) {
    const tasks = await db.task.findMany();
    return new Response(JSON.stringify({ data: tasks }), {
        headers: { 'Content-Type': 'application/json' },
    });
}

This code imports the database instance, retrieves all tasks using findMany, and sends them back as a JSON response.

Step 8: Sending the Response

The response is sent using the Response object. You can wrap the request and response objects in Next.js for additional functionality, but for this example, the basic web API will suffice.

Conclusion

With these steps, you have set up a basic route handler that responds to GET requests by retrieving data from your database. You can extend this setup to handle other HTTP methods and perform various actions on your server.

In the next video, we will demonstrate how to handle POST requests using Thunder Client.

Post a Comment

0Comments

Post a Comment (0)