Accessing an API Route
You can access an API route from your frontend code (React components) using techniques like fetch or libraries like Axios. Here’s an example using fetch:
// app/page.js
'use client'
import React, { useState, useEffect } from 'react';
const HelloWorldComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api') // Relative URL to your API route
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error(
'Error fetching data:', error));
}, []);
return (
<div>
{data ? (
<p style={{ fontSize: '50px' }}>
Hello: {data.hello}
</p>
) : (
<p>Loading...</p>
)}
</div>
);
};
export default HelloWorldComponent;
Output:
How to use Next.js API Routes?
Next.js API Routes are a feature of Next.js that allows you to create server-side logic and APIs within your Next.js application. These API routes are implemented using files in the `pages/api` directory of your Next.js project. When you deploy your Next.js application, these API routes are automatically served as serverless functions.
Table of Content
- Key points about Next.js API Routes
- Dynamic API Routes
- Creating an API Route
- API Routes custom configuration
- Typing API Routes with TypeScript
- Accessing an API Route
- Conclusion