DEV Community

Turing
Turing

Posted on

Nextjs API Post Example

In Next.js, an API POST request refers to a type of request that allows a client (such as a web browser or an application) to send data to the server. When using the POST method in an API, the client is typically providing some kind of information to the server, such as user data from a form or information to create a new resource (like a new user or a new entry in a database).

For example, if you're submitting a form on a website, such as registering for an account, the data you enter (name, email, etc.) is usually sent to the server using a POST request. The server then processes that data, stores it, or performs some action, and responds back.

In Next.js, when handling a POST request, you:

Set up an API route on the server side to receive the data.
Allow the client (such as your web app) to send data in the body of the request.
On the server side, you process this data, perform actions like storing it in a database, and respond accordingly (e.g., confirming the data was saved).
The POST method is commonly used when you need to send sensitive or complex data to the server, as opposed to GET requests, which are used to simply request data from the server.

Before we jump to examples. i'd recommend you to try gpteach.us to learn nextjs and typescript. it's AI tool pitching you code and tasks.

Example 1: Contact Form Submission
This example demonstrates how to handle a POST request where a user submits a contact form with their name and message.

Server-Side: Next.js API Route


// pages/api/contact.js

export default function handler(req, res) {
  if (req.method === 'POST') {
    const { name, message } = req.body; // Extract name and message from the request body

    if (!name || !message) {
      res.status(400).json({ error: 'Name and message are required.' });
      return;
    }

    // Process the data (e.g., save to database, send an email, etc.)
    res.status(200).json({ success: `Message from ${name} received!` });
  } else {
    // Only allow POST requests
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} not allowed`);
  }
}

Enter fullscreen mode Exit fullscreen mode

client side:


// Example React Component to submit the contact form

function ContactForm() {
  const handleSubmit = async (event) => {
    event.preventDefault();
    const formData = {
      name: event.target.name.value,
      message: event.target.message.value,
    };

    const response = await fetch('/api/contact', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    });

    const result = await response.json();
    console.log(result); // Handle response (success or error message)
  };

  return (
    <form onSubmit={handleSubmit}>
      <input name="name" type="text" placeholder="Your Name" required />
      <textarea name="message" placeholder="Your Message" required></textarea>
      <button type="submit">Send</button>
    </form>
  );
}


Enter fullscreen mode Exit fullscreen mode

Example 2: Creating a New User
This example demonstrates how to handle a POST request to create a new user account by receiving the user's name, email, and password.

Server-Side: Next.js API Route

// pages/api/register.js

export default function handler(req, res) {
  if (req.method === 'POST') {
    const { name, email, password } = req.body; // Extract user data from the request body

    if (!name || !email || !password) {
      res.status(400).json({ error: 'Name, email, and password are required.' });
      return;
    }

    // Simulate saving the user to a database
    const newUser = { id: Date.now(), name, email };

    // Respond with the newly created user data
    res.status(201).json({ message: 'User created', user: newUser });
  } else {
    // Only allow POST requests
    res.setHeader('Allow', ['POST']);
    res.status(405).end(`Method ${req.method} not allowed`);
  }
}
Enter fullscreen mode Exit fullscreen mode

client side:

// Example React Component to register a new user

function RegisterForm() {
  const handleRegister = async (event) => {
    event.preventDefault();
    const formData = {
      name: event.target.name.value,
      email: event.target.email.value,
      password: event.target.password.value,
    };

    const response = await fetch('/api/register', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(formData),
    });

    const result = await response.json();
    console.log(result); // Handle response (success or error message)
  };

  return (
    <form onSubmit={handleRegister}>
      <input name="name" type="text" placeholder="Your Name" required />
      <input name="email" type="email" placeholder="Your Email" required />
      <input name="password" type="password" placeholder="Your Password" required />
      <button type="submit">Register</button>
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

These examples show how to handle POST requests in Next.js API routes and send data from a client-side form to the server. Each example processes the data and sends a response based on the request.

Top comments (0)