Creating Data with POST

Introduction: Understanding the POST Method

Welcome! In this lesson, we will focus on the POST method, which is a key part of working with data in web applications. The POST method is used when you want to create new data on the server, such as adding a new user to a database.

When you fill out a form on a website and click "submit," your browser often sends a POST request to the server. The server then processes the data and stores it. Learning how to handle POST requests is an important first step in building your own backend APIs.

By the end of this lesson, you will know how to accept data from a client, validate it, and add it to your data store using Next.js API routes.


Quick Setup Recap: Next.js API Route and Data Store

Before we dive into handling POST requests, let’s quickly review the basic setup you’ll be working with. In this course, we use a Next.js API route to handle requests, and we store our user data in a simple in-memory array.

Here’s a summary of the setup:

import { NextResponse, type NextRequest } from 'next/server';
import { users, type User } from '@/lib/data';

/**
 * Handles GET requests to /api/users.
 * Retrieves and returns a list of all users.
 */
export async function GET(request: NextRequest) {
  return NextResponse.json(users);
}
  • We import NextResponse and NextRequest from Next.js to handle API requests and responses.
  • The users array holds our user data in memory (not in a real database).
  • The GET function returns all users as a JSON response.

Note: Keep in mind that in-memory storage is temporary—if the server restarts, the data will be lost. In a production application, this logic would typically interact with a persistent database like PostgreSQL, MongoDB, or SQLite. We're using an array here to simplify the focus on API logic rather than database setup.

This setup allows us to focus on how to handle POST requests without worrying about database setup for now.


Handling POST Requests in Next.js

To create new data, we need to handle POST requests in our API route. In Next.js App Router, each HTTP method corresponds to a separate function (GET, POST, PUT, etc.) that you export from the same file.

In real-world applications, you might also need to configure CORS (Cross-Origin Resource Sharing) or set headers such as Content-Type: application/json on the client request. While this is handled automatically in many setups, it's worth being aware of when integrating with other frontends or third-party tools.

Here’s how you can define a POST handler:

export async function POST(request: NextRequest) {
  try {
    const newUser: Omit<User, 'id'> = await request.json();

    // Basic validation
    if (!newUser.name || !newUser.email) {
      return NextResponse.json(
        { error: 'Name and email are required' },
        { status: 400 }
      );
    }

    // Generate a new ID (in a real DB, this is handled automatically)
    // This way, the first user will get an ID of 1
    const newId = Math.max(...users.map(u => u.id), 0) + 1;
    
    const userWithId: User = {
      id: newId,
      ...newUser,
    };

    // Add the new user to our in-memory array
    users.push(userWithId);

    // Return the newly created user with a 201 status code
    return NextResponse.json(userWithId, { status: 201 });
  } catch (error) {
    return NextResponse.json(
      { error: 'Invalid request body' },
      { status: 400 }
    );
  }
}

Let’s break down what’s happening here:

  • The function receives a request object.
  • It reads the JSON body from the request using await request.json().
  • It checks if the required fields (name and email) are present.
  • If validation fails, it returns an error with status code 400 (Bad Request).
  • If validation passes, it creates a new user object with a unique ID.
  • The new user is added to the users array.
  • The function returns the new user with a status code of 201 (Created).

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal