How to set up and use API routes in Next.js



Image not found!!

In Next.js, API routes are used to create serverless functions that can handle backend logic. These routes are stored in the pages/api directory and automatically become part of your Next.js application. Here's a step-by-step guide on how to set up and use API routes in Next.js:

Step 1: Create the API route

  1. Create the pages/api directory: Inside your Next.js project, create a folder named api inside the pages directory. This is where you'll store your API route files.

    bash
    mkdir pages/api
  2. Create an API route file: Inside the pages/api directory, create a new file for your API route. For example, create a file named example.js.

    javascript
    // pages/api/example.js export default function handler(req, res) { res.status(200).json({ message: 'Hello from the API!' }); }

Step 2: Use the API route in your application

Now that you've created the API route, you can use it in your components or pages.

  1. Fetch data in a component or page: You can use the fetch API or any other HTTP library to make a request to your API route.

    javascript
    // pages/index.js import React, { useEffect, useState } from 'react'; const Home = () => { const [data, setData] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await fetch('/api/example'); const result = await response.json(); setData(result); } catch (error) { console.error('Error fetching data:', error); } }; fetchData(); }, []); return ( <div> <h1>Hello Next.js</h1> {data && <p>{data.message}</p>} </div> ); }; export default Home;

    In this example, the component fetches data from the example API route and displays the result.

Step 3: Start your Next.js application

Run your Next.js application:

bash
npm run dev

Visit http://localhost:3000 in your browser, and you should see your application displaying the data fetched from the API route.

That's it! You've successfully set up and used an API route in Next.js. You can now expand your API routes to handle more complex logic, database queries, or external API requests.