Next.js Tutorial
Selected Reading
- Next.js - Discussion
- Next.js - Useful Resources
- Next.js - Quick Guide
- Next.js - CLI
- Next.js - Deployment
- Next.js - Environment Variables
- Next.js - Typescript
- Next.js - Response Helpers
- Next.js - API MiddleWares
- Next.js - API Routes
- Next.js - Shallow Routing
- Next.js - Imperitive Routing
- Next.js - Dynanic API Routes
- Next.js - Routing
- Next.js - Pre-Rendering
- Next.js - Global CSS Support
- Next.js - CSS Support
- Next.js - Meta Data
- Next.js - Static File Serving
- Next.js - Pages
- Next.js - Environment Setup
- Next.js - Overview
- Next.js - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Next.js - API MiddleWares
Next.js - API MiddleWares
API Routes in Next.JS have built-in middlewares which helps in parsing the incoming request.
Following are the middlewares
req.cookies − cookies object contains the cookies sent by the request. Default value is {}.
req.query − query object contains the query string. Default value is {}.
req.body − query object contains the request body parsed using content-type . Default value is null.
Let s create an example to demonstrate the same.
In this example, we are going to update an user.js in pages/api directory.
Let s update the nextjs project used in
chapter.Create user.js file in pages/api directory as following.
export default (req, res) => { res.statusCode = 200 res.setHeader( Content-Type , apppcation/json ) res.end(JSON.stringify({ query: req.query })) }
Start Next.js Server
Run the following command to start the server −.
npm run dev > nextjs@1.0.0 dev D:Node extjs > next ready - started server on http://localhost:3000 info - Loaded env from D:Node extjs.env.local event - compiled successfully event - build page: /api/user wait - compipng... event - compiled successfully event - build page: /next/dist/pages/_error wait - compipng... event - compiled successfully
Verify Output
Open http://localhost:3000/api/user?counter=1 in a browser and you will see the following output.
{"query":{"counter":"1"}}Advertisements