When the app router was released in NextJS 13.2 , being a frontend developer, I was stuck with building API's for my project. But NextJS solved it finally by letting us create API endpoints for our application. Personally, I think building something with this in large scale is still a no-time-soon for now, but for small projects & frontend developers, this was a dream come true.
In this tutorial, I am not going to cover detail topics on how to use route handlers and all. I hope you know the basics. One thing I was stuck with was handling form data for POST request. So, I am going to explain that in a second. But let's start with the installation and other stuffs.
Prerequisite
- Latest version of NodeJS must be installed.
- Basic knowledge of HTTP requests will be added benefit.
- Understanding of useState() hook in react.
Installation
After installing NodeJS, open a terminal and navigate to a directory of your choice using
cd path/to/project/directory
.Then start a next app using
npx create-next-app@latest usingapidirectory
, you can name your project name anything you want, I have named itusingapidirectory
.Get inside the project directory using
cd usingapidirectory
Then, let's get the app running by using
npm run dev
in your project directory in the terminal.Open http://localhost:3000/ in your browser and see the result.
Code Editing
Open your project in the code editor.
Inside the app directory, open the
page.js
file and replace everything with:
"use client"
import { useState,useEffect } from "react"
export default function Home() {
return (
// Your code goes here
)
}
- Also, for clarity, delete everything from
globals.css
and replace it with: ```
@tailwind base;
@tailwind components;
@tailwind utilities;
### Defining our state and form layout
We will be building a simple form that accepts to fields: name and age. So let's define a state for that.
Inside the app/page.js:
"use client"
import { useState, useEffect } from "react"
export default function Home() {
const [name, setName] = useState('')
const [age, setAge] = useState('')
return (
// Your code goes here
GET & POST Request in NextJS Stable App Router
type="text"
name="name"
placeholder="Enter the name"
onChange={e => setName(e.target.name)}
className=" border p-2 px-4 rounded outline-none "
/>
type="number"
name="age"
placeholder="Enter the age"
onChange={e => setAge(e.target.name)}
className=" border p-2 px-4 rounded outline-none "
/>
type="submit"
className=" border-blue-500 bg-blue-500 text-white p-2 px-4 rounded-md "
>Submit
)
}
It's a basic layout of our form that we are going to use. Styling is just to make it beautiful, don't bother if you don't want to.
### Creating API
1. First, create a folder named `api` inside the app directory. This is a must and if you are like "What?", "Why?", "How?", then I am pretty sure you should not read below this, first see the NextJS documentation on [app routes](https://nextjs.org/docs/pages/building-your-application/routing/api-routes).
2. Inside the api directory, create a folder named `handleform`.
3. Now this is how you basically create an API endpoint in your NextJS application.
4. Your api is available at `/api/handleform`. Sorry, not now. Wait!!!
Let's go.
### Disclaimer! Did somebody said GET this.
Handling GET request is extremely easy. For this project we are not going to use GET request since we want to handle form data using POST request. But here's a code that goes that will create an api get request
import { NextResponse } from "next/server";
export async function GET(){
const data = {
name: 'Bishal Shrestha',
age: '27'
}
return NextResponse.json({data})
}
Now you can check in postman or any other api testing tool and see for yourself. http:localhost:3000/api/handleform
### Handling POST request
I told you earlier, this is what we are for in this tutorial. When I was learning NextJS, I got stuck here for like forever. Don't worry, you are not going to because I am here.
Questions:
1. Have you never ever used POST request in Next app?
2. Are you stuck in POST request handling request.body?
3. Do you like Twitter over Threads?
You are in.
Let's go.
Boom!!!
export async function POST(req,res){
const data =await req.json()
console.log(data)
return NextResponse.json(data)
}
This is it. Yoooooooooho.
Hold on! What is this?
Let me answer, this is how you handle POST request using `req.json()`, and not `req.body`
Let's see how this works.
Let's create a handleSubmit method in our `app/page.js` file.
const handleSubmit = async (e) => {
e.preventDefault()
const submitData = {name,age}
try {
const res = await fetch('http://localhost:3000/api/handleform',{
method: 'POST',
body: JSON.stringify(submitData),
headers: {
'content-type': 'application/json'
}
})
console.log(res)
if(res.ok){
console.log("Yeai!")
}else{
console.log("Oops! Something is wrong.")
}
} catch (error) {
console.log(error)
}
setName('')
setAge('')
}
Make sure to pass this method in the form tag.
`<form onSubmit={handleSubmit} ............. />`
I hope I helped. Peace.
Full code available [here](https://github.com/iambstha/blog-post-request-nextjs-app-router) in GitHub.
Top comments (9)
You are a life saver !!!
Thank you.
This is the most incoherent and useless post. In
/api/handleform
there's NO request URL. How does this even make sense??Try it before you say it.
what about sending files
The context of this post is around Get and Post request in NextJS only.
Thank you very much. It helped a lot
How would you pass a CSRF token in your fetch request? Did something similar to you and even added X-CSRF-Token: csrfToken on the headers and couldn't get it to pass a security check
Check this