DEV Community

Bishal Shrestha
Bishal Shrestha

Posted on

HTTP GET & POST Request in NextJS Stable App Router

Image description
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

  1. Latest version of NodeJS must be installed.
  2. Basic knowledge of HTTP requests will be added benefit.
  3. Understanding of useState() hook in react.

Installation

  1. After installing NodeJS, open a terminal and navigate to a directory of your choice using cd path/to/project/directory.

  2. Then start a next app using npx create-next-app@latest usingapidirectory, you can name your project name anything you want, I have named it usingapidirectory.

  3. Get inside the project directory using cd usingapidirectory

  4. Then, let's get the app running by using npm run dev in your project directory in the terminal.

  5. Open http://localhost:3000/ in your browser and see the result.

Code Editing

  1. Open your project in the code editor.

  2. 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
  )
}
Enter fullscreen mode Exit fullscreen mode
  1. Also, for clarity, delete everything from globals.css and replace it with:
@tailwind base;
@tailwind components;
@tailwind utilities;
Enter fullscreen mode Exit fullscreen mode

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
    <div className=" flex flex-col justify-center items-center w-full p-8 ">
      <h1 className=" w-full text-center m-4 font-semibold text-lg ">GET & POST Request in NextJS Stable App Router</h1>
      <form className=" flex w-full flex-col justify-center items-center ">
        <div className=" flex w-1/2 justify-center items-center gap-4 ">
          <input
            type="text"
            name="name"
            placeholder="Enter the name"
            onChange={e => setName(e.target.name)}
            className=" border p-2 px-4 rounded outline-none "
          />
          <input
            type="number"
            name="age"
            placeholder="Enter the age"
            onChange={e => setAge(e.target.name)}
            className=" border p-2 px-4 rounded outline-none "
          />
          <button 
          type="submit" 
          className=" border-blue-500 bg-blue-500 text-white p-2 px-4 rounded-md " 
          >Submit</button>
        </div>
      </form>
    </div>
  )
}
Enter fullscreen mode Exit fullscreen mode

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.

  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})
}
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

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('')
  }
Enter fullscreen mode Exit fullscreen mode

Make sure to pass this method in the form tag.
<form onSubmit={handleSubmit} ............. />

I hope I helped. Peace.
Full code available here in GitHub.

Top comments (5)

Collapse
 
pradneyasp profile image
Pradneya Prabhudesai

You are a life saver !!!

Collapse
 
iambstha profile image
Bishal Shrestha

Thank you.

Collapse
 
sh20raj profile image
Sh Raj

what about sending files

Collapse
 
kkv007 profile image
Kanoj

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

Collapse
 
iambstha profile image
Bishal Shrestha

Check this