Next.js DELETE HTTP Request
Next.js is a React framework that allows developers to build server-side rendered (SSR) or statically generated web applications. Let’s explore the intricacies of Next.js DELETE HTTP Request.
1. Overview of Next.js
1.1 Key Features of Next.js
- Server-side Rendering (SSR): Next.js enables server-side rendering out of the box, improving performance and SEO by generating HTML on the server for each request.
- Static Site Generation (SSG): Next.js supports static site generation, allowing developers to pre-render pages at build time for improved performance and lower hosting costs.
- Automatic Code Splitting: Next.js automatically splits JavaScript code into smaller chunks, ensuring that only necessary code is loaded for each page, resulting in faster load times.
- Client-side Routing: Next.js provides a simple and intuitive routing system that allows for seamless navigation between pages without full page reloads.
- API Routes: With Next.js, developers can easily create API routes to handle server-side logic and data fetching, making it ideal for building full-stack applications.
- Zero Configuration: Next.js requires minimal setup and configuration, allowing developers to focus on writing code rather than configuring tools.
- Hot Module Replacement (HMR): Next.js supports hot module replacement, enabling instant updates to the application code during development without the need for full page reloads.
- Static File Serving: Next.js serves static assets like images, stylesheets, and fonts efficiently, improving overall performance.
- Dynamic Imports: Next.js allows for dynamic imports, enabling lazy loading of components and routes, further optimizing performance.
1.2 Advantages of Using Next.js
Next.js offers several advantages for web development:
- Improved Performance: Next.js optimizes performance through server-side rendering, automatic code splitting, and static site generation.
- Enhanced SEO: Server-side rendering and static site generation improve SEO by ensuring that search engines can crawl and index content effectively.
- Streamlined Development: Next.js simplifies development with features like zero configuration, hot module replacement, and built-in routing.
- Scalability: Next.js is highly scalable and can be used to build small projects as well as large-scale applications.
- Flexibility: Next.js provides flexibility in choosing between server-side rendering, static site generation, or a combination of both based on project requirements.
- Full-stack Capabilities: With support for API routes, Next.js enables developers to build full-stack applications using a single framework.
2. Code Example
Creating a “Hello, World!” application in Next.js is straightforward. Next.js is a React framework that enables server-side rendering and simplifies the creation of React applications. Here’s a simple step-by-step guide to creating a “Hello, World!” application in Next.js:
2.1 Setting up Node Js
Ensure that Node.js and npm (Node Package Manager) are installed on your system. It’s recommended to use a Node.js version greater than 18 when working with Next.js.
2.2 Creating a Backend Application
To understand the Next.js and http api interaction we need to create a backend application using the express.js framework. You can refer to this article to understand and download a sample backend application.
2.3 Create a new Next.js app
You have the option to initiate a new Next.js application using the create-next-app
command, a tool provided by the Next.js team.
npx create-next-app next-http-app
Executing this command will generate a fresh directory named next-http-app
and initialize a new Next.js project within it. The command will present prompts for inputs (such as TypeScript or JavaScript app and using default CSS or SCSS), allowing you to make decisions based on your requirements.
2.4 Navigate into the project directory
Navigate to the project directory and modify the src/app/page.tsx
typescript file. By default, Next.js creates a simple homepage. Open this file and replace its contents with the following:
"use client"; import { useEffect, useState } from "react"; type User = { id: number; first_name: string; last_name: string; email: string; gender: string; phone: string; }; const Home = () => { const [data, setData] = useState<User[]>([]); const [deleteSuccessMessage, setDeleteSuccessMessage] = useState(""); useEffect(() => { const fetchData = async () => { try { const res = await fetch("http://localhost:10091/users"); const responseData = await res.json(); setData(responseData.info); } catch (err) { console.error(err); } }; fetchData(); }, []); const handleDelete = async (id: number) => { try { await fetch(`http://localhost:10091/users/${id}`, { method: "DELETE" }); setData(data.filter((user) => user.id !== id)); // Remove the deleted user from the state setDeleteSuccessMessage("Delete successful"); // Automatically hide the delete success message after 1 minute setTimeout(() => { setDeleteSuccessMessage(""); }, 60000); } catch (err) { console.error(err); } }; return ( <main> <div> <h1>Next.js - HTTP GET and DELETE HTTP calls example</h1> {deleteSuccessMessage && <div>{deleteSuccessMessage}</div>} <table> <thead> <tr> <th>first name</th> <th>last name</th> <th>email address</th> <th>gender</th> <th>phone number</th> <th>Action</th> {/* Add a column for delete button */} </tr> </thead> <tbody> {data.map((user) => ( <tr key={user.id}> <td>{user.first_name}</td> <td>{user.last_name}</td> <td>{user.email}</td> <td>{user.gender}</td> <td>{user.phone}</td> <td> <button onClick={() => handleDelete(user.id)}>Delete</button>{" "} {/* Add delete button */} </td> </tr> ))} </tbody> </table> </div> </main> ); }; export default Home;
2.4.1 Explanation
This piece of code represents a React component named “Home,” which retrieves information from a RESTful API endpoint (http://localhost:10091/users) via the HTTP GET method. Subsequently, it presents this data in a table format. Furthermore, it incorporates a delete feature enabling the removal of users from the displayed list, accomplished through the utilization of the HTTP DELETE method.
Here’s a breakdown of what each part does:
- Imports: It imports necessary functions and types from the React library.
- Type Definition: Defines a TypeScript type User representing the structure of a user object.
- Home Component: Defines a functional component called Home.
- State Initialization: Initializes state variables data to hold an array of User objects fetched from the API and deleteSuccessMessage to hold a message indicating successful deletion.
- Fetching Data: Uses the useEffect hook to fetch data from the API when the component mounts. It updates the data state with the fetched user information.
- Delete Handler: Defines a function handleDelete to handle the deletion of a user. It sends a DELETE request to the API endpoint for the specified user ID. Upon successful deletion, it updates the data state by filtering out the deleted user and setting a success message. It also schedules hiding the success message after 1 minute using setTimeout.
- Rendering: Renders the UI including a heading, a delete success message (if any), and a table with user data. For each user in the data state, it renders a table row (<tr>) with user details and a delete button (<button>) which calls the handleDelete function when clicked.
- Export: Exports the Home component as the default export.
Next.js provides the default CSS setup. To disable the default CSS, you can comment out the code in the src/app/globals.css
file.
3. Run the development server
npm run dev
This command will start the development server, and you’ll be able to see your Next.js app running on http://localhost:3000
. If the port is already in use, Next.js will automatically switch to a different port. If you need to specify a custom port, update the scripts
tag in the package.json
file as shown below.
"scripts": { "dev": "next dev -p 8200", "build": "next build", "start": "next start -p 8202", "lint": "next lint" }
Once the developer server is up you can see the changes reflected in your browser at http://localhost:8200
.
When you click the delete button, the user record will be removed, and a confirmation message will be displayed.
4. Conclusion
In conclusion, understanding the process of sending an HTTP DELETE call to a backend application and observing the subsequent results is crucial for modern web development. This fundamental operation forms the backbone of many interactions between frontend and backend systems, enabling the deletion of data and facilitating dynamic content management. By delving into the intricacies of HTTP requests and responses, developers gain a deeper comprehension of how information flows across the web, empowering them to build robust and efficient applications. Additionally, mastering this aspect of web development fosters enhanced problem-solving skills and paves the way for creating seamless user experiences. Ultimately, the ability to effectively utilize HTTP DELETE calls contributes to the creation of responsive, interactive, and feature-rich web applications that meet the evolving needs of users in today’s digital landscape.
5. Download the Code
The tutorial offered guidance on how to trigger an HTTP DELETE request to a backend application and observe the outcomes.
You can download the full source code of this example here: HTTP DELETE call in Next.js