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 a…


This content originally appeared on DEV Community and was authored by Dimas Priyandi

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' })
}

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

   npx create-next-app@latest

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`);
  }
}

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.


This content originally appeared on DEV Community and was authored by Dimas Priyandi


Print Share Comment Cite Upload Translate Updates
APA

Dimas Priyandi | Sciencx (2024-07-20T09:45:46+00:00) Create API Routes Using Next Js. Retrieved from https://www.scien.cx/2024/07/20/create-api-routes-using-next-js/

MLA
" » Create API Routes Using Next Js." Dimas Priyandi | Sciencx - Saturday July 20, 2024, https://www.scien.cx/2024/07/20/create-api-routes-using-next-js/
HARVARD
Dimas Priyandi | Sciencx Saturday July 20, 2024 » Create API Routes Using Next Js., viewed ,<https://www.scien.cx/2024/07/20/create-api-routes-using-next-js/>
VANCOUVER
Dimas Priyandi | Sciencx - » Create API Routes Using Next Js. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/07/20/create-api-routes-using-next-js/
CHICAGO
" » Create API Routes Using Next Js." Dimas Priyandi | Sciencx - Accessed . https://www.scien.cx/2024/07/20/create-api-routes-using-next-js/
IEEE
" » Create API Routes Using Next Js." Dimas Priyandi | Sciencx [Online]. Available: https://www.scien.cx/2024/07/20/create-api-routes-using-next-js/. [Accessed: ]
rf:citation
» Create API Routes Using Next Js | Dimas Priyandi | Sciencx | https://www.scien.cx/2024/07/20/create-api-routes-using-next-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.