DEV Community

Cover image for Create API Routes Using Next Js
Dimas Priyandi
Dimas Priyandi

Posted on

Create API Routes Using Next Js

What Is Next Js ?
Next Js is a React Framework for building full stack web applications
You use React Components to build user interfaces, and Next.js for additional features and optimizations.

Main Features
You can use many feature in next js such as Routing,Rendering, Data Fetching and Styling sections. Of course you can dive deeper for learn about Optimizing and Configuring.

API Routes Next Js
API Routes provide a solution to build a public API with next js.

Any file inside the folder pages/api is mapped to /api/ and will be treated as an API endpoint instead of a page. They are server-side only bundles and won't increase your client-side bundle size.

For example , the following API route returns a JSON response with a status code of 200 or success :

import type { NextApiRequest, NextApiResponse } from 'next'

type ResponseData = {
  message: string
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  res.status(200).json({ message: 'success' })
}
Enter fullscreen mode Exit fullscreen mode

Build Your Application
First, Install next js using terminal in your terminal and following this steps:

   npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

On installation, you'll see the following prompts::

Image description

After we following from above command, folder was created with your project name and install the required dependencies.

Project Structure
If project has been created in your directory , we can look project structure in this below:
Image description
so we ready for run this app

Run the Development Server

  1. Run npm run dev to start the development server
  2. Visit http://localhost:3000 to view your application 3. Edit app/page.tsx (or pages/index.tsx) file and save it to see the changes result in your browser

Implementation API Routes in Next Js
Now , we create a file typescript with name hello.ts in pages/api . In this file we will handle different HTTP methods in an API route, you can use req.method in your request handler, like so :

// pages/api/hello.ts

import type { NextApiRequest, NextApiResponse } from 'next';

type ResponseData = {
  message: string;
};


export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  if (req.method === 'GET') {
    res.status(200).json({ message: 'success' });
  } else {
    res.setHeader('Allow', ['GET']);
    res.status(405).end(`Method ${req.method} Not Allowed`);
  }
}

Enter fullscreen mode Exit fullscreen mode

Test Your App
Now you can test your endpoint in postman or curl with access localhost:3000/api/hello
So you can get response with status code 200 and get message from response body

Congratulation, now you can create API Routes using next js.

Top comments (0)