How to send a post request to external api in next.js

Cover Image for How to send a post request to external api in next.js
Ali Bentaleb

To send post request to an external api in a react app like next.js, use fetch and specify the post method like this : fetch(‘/api/’, { method: “POST”})

In this tutorial, we are going to show an example of sending post request to an external api

Send to external API

We are going to build an input and button and when clicked it will send a request to our external api

Under pages/test.js

import Head from "next/head";
import { useState } from "react";

export default function Test() {
  const [todo, setTodo] = useState({todo:''});
  const [data, setData] = useState();

  const onSubmit = async (e) => {
    e.preventDefault();
    if (todo.todo === "" )
      return alert("todo is empty");

    await fetch("/api/myform", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(todo),
    })
      .then((res) => res.json())
      .then((data) => setData(data.todo));
  };
  return (
    <div>
      <Head>
        <title> Next.js send post to external API</title>
      </Head>

      <form
        onSubmit={onSubmit}
        className="w-1/3 justify-center border-2 flex flex-col gap-4 m-4 p-2"
      >
        <label htmlFor="Last name">Todo name</label>
        <input
          className="border-2 border-gray-200  p-2"
          onChange={() => {
            setTodo({todo:event.target.value});
          }}
        ></input>

        <button
          className="bg-black text-white text-sm font-medium p-2 rounded "
          type="submit"
        >
          <>Submit</>
        </button>
      </form>
      <div className="p-2">{data ? "todo is : " + data : ""}</div>
    </div>
  );
}

}


The form will submit its data to an external API

fetch is used to send the request to the external API, as options we specify the http verb, the headers and then we turned our js object into a json using json.stringify so that our back end will understand the body of the request

Test configuration

Run your server and hit localhost:3000 or whatever port you are using for dev server

Now when you type in the fields and you hit submit you get the result returned by the API below the form like this:

submit external api post

Conclusion

We have seen how to post a request to an external api

You might be interested on how to submit your form to an api in general, so i recommend to check my article in [this link]

you might also like to know how to validate data on client side like emails and input, you can find more details in this link

Loading Screen on Next.js page...Easy doughnut and bar charts w...