This guide explains how to create and consume API routes in Next.ts while using a service-based approach for client-side API calls.
Create a new API route in src/app/api/hello/route.ts
:
import { NextResponse } from 'next/server'; export async function GET() { return NextResponse.json({ message: "Hello, API!" }); }
Run the following command:
npm install axios
Define a reusable service in src/services/ApiService.ts
:
import axios from 'axios'; export async const fetchData = async (url: string): Promise =>{ const response = await axios.get(url); return response.data; }
Use the API service inside a React component:
'use client'; import { useEffect, useState } from 'react'; import { fetchData } from '../services/ApiService'; export default function HelloWorld() { const [message, setMessage] = useState(''); useEffect(() => { fetchData<{ message: string }>('/api/hello') .then(data => setMessage(data.message)) .catch(error => console.error(error)); }, []); return
{message}
; }
Be the first to know about new updates and exclusive discounts. No spam, just great offers!
How about
With over 7 years of experienced team, we specialize in delivering custom projects for startups, blue-chip companies, and government agencies. We have successfully completed over 250+ projects, providing tailored solutions that meet the unique needs of each client.
Hire Us© 2025 Domiex Created & Crafted by SRBThemes.