How to host React Applications on NetSuite ERP the right way?
6 min read
Dec 13, 2024
Published on
Dec 13, 2024
Rishabh
6 mins
Next.js is an amazing framework for developing React applications, and it includes a built-in API routing system that makes creating backend endpoints very easy. This guide will show you how to create API routes in a Next.js application, work with RESTful endpoints, and deal with dynamic parameters.
In Next.js, APIs, i.e., Application Programming Interfaces, allow you the opportunity to create and define backend functionalities in the same project, thus making it easy to build complex and innovative applications all in one place. API routes refer to the cases in which each individual file in the pages/api directory is an endpoint that allows you to make requests (GET, POST, PUT, DELETE) without the need to set up an external server.
Create a new Next.js project if you don’t already have one:
npx create-next-app@latest next-api-demo
cd next-api-demo
Run the development server:
npm run dev
Your project will be available at http://localhost:3000.
1. Inside your Next.js project, navigate to the pages/api directory.
2. Create a new file, for example, hello.js.
export default function handler(req, res) {
res.status(200).json({ message: "Hello, Next.js API!" });
}
Open your browser and navigate to http://localhost:3000/api/hello. You should see
the JSON response:
{ "message": "Hello, Next.js API!" }
API routes in Next.js can handle various HTTP methods. Let’s create an endpoint that processes both GET and POST requests.
1. Create a file named users.js inside pages/api.
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ users: ["Alice", "Bob", "Charlie"] });
} else if (req.method === 'POST') {
const { name } = req.body;
if (!name) {
return res.status(400).json({ error: "Name is required" });
}
res.status(201).json({ message: `User ${name} added` });
} else {
res.setHeader("Allow", ["GET", "POST"]);
res.status(405).json({ error: `Method ${req.method} Not Allowed`
});
}
2. Test the endpoint:
○ GET /api/users: Returns a list of users.
○ POST /api/users (with a JSON body like {"name": "Dave"}): Adds a user.
Next.js supports dynamic routes for APIs, allowing you to work with parameters. For example, create an endpoint to fetch, update, or delete a user by ID.
1. Create a file named [id].js inside pages/api/users.
export default function handler(req, res) {
const { id } = req.query; // Access dynamic route parameters
if (req.method === 'GET') {
res.status(200).json({ user: { id, name: `User ${id}` } });
} else if (req.method === 'DELETE') {
res.status(200).json({ message: `User ${id} deleted` });
} else {
res.setHeader("Allow", ["GET", "DELETE"]);
res.status(405).json({ error: `Method ${req.method} Not Allowed`
});
}
}
Test the endpoint:
○ GET /api/users/1: Fetch details for users with ID 1.
○ DELETE /api/users/1: Simulate deleting the user with ID 1.
For a more organized RESTful structure, you can group endpoints under directories. For
example:
● GET /api/products: Fetch all products.
● GET /api/products/[id]: Fetch a product by ID.
● POST /api/products: Create a new product.
● PUT /api/products/[id]: Update a product by ID.
● DELETE /api/products/[id]: Delete a product by ID.
Directory structure:
pages/
├── api/
│ ├── products/
│ │ ├── [id].js
│ │ └── index.js
index.js (Handle GET and POST for all products):
export default function handler(req, res) {
if (req.method === 'GET') {
res.status(200).json({ products: [{ id: 1, name: "Product A" }]
});
} else if (req.method === 'POST') {
const { name } = req.body;
if (!name) {
return res.status(400).json({ error: "Product name is required"
});
}
res.status(201).json({ message: `Product ${name} created` });
} else {
res.setHeader("Allow", ["GET", "POST"]);
res.status(405).json({ error: `Method ${req.method} Not Allowed`
});
}
}
[id].js (Handle GET, PUT, and DELETE for a single product):
export default function handler(req, res) {
const { id } = req.query;
if (req.method === 'GET') {
res.status(200).json({ id, name: `Product ${id}` });
} else if (req.method === 'PUT') {
const { name } = req.body;
if (!name) {
return res.status(400).json({ error: "Product name is required"
});
}
res.status(200).json({ message: `Product ${id} updated to ${name}`
});
} else if (req.method === 'DELETE') {
res.status(200).json({ message: `Product ${id} deleted` });
} else {
res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
res.status(405).json({ error: `Method ${req.method} Not Allowed`
});
}
}
Use tools like Postman, or curl to test your API routes by sending different HTTP requests. Best Practices for Next.js API Routes
1. Validation: Validate incoming requests using libraries like joi or yup.
2. Error Handling: Provide meaningful error messages and use consistent status codes.
3. Middleware: Use middleware for tasks like authentication or logging.
4. Environment Variables: Store sensitive data like API keys in .env.local.
5. Separate Logic: Extract business logic into separate files or modules to keep API routes clean.
Next.js API routes offer an easy but still very powerful functionality of backend development right inside the application. By utilizing its resourceful routing as well as allowing different HTTP methods, it is possible to compose RESTful APIs in a quick way. Coupled with good practices, this will become a solid and reliable system you can bring to production.
Insights