Next.js Validate request using Next-Connect and Express-Validator
you need validate your API request when someone tries to POST, PUT and etc.
in this article I tried to validate requests using next-connect ,express-validator so lets start it
1-Setup :
you have to install express-validator and next-connect to your project using and wait until finished.
npm i next-connect express-validator --save
2-Creating Middleware Handler :
I will be use next-connect as global Middleware so lets create folder named middleware and create handler.js./middleware/handler.js
so as you can see we created or handler to handle middleware and handle our validations as easy as you can see to learn more about next-connect visit : https://www.npmjs.com/package/next-connect
3-Use handle in a API URL :
so we created handler now its time to use it in our API we know that next-connect provide router system like Express.js so we don’t need to use Next.js default API switch case statement just need to use .post()
for POST method and .get()
for GET method and same for PUT, DELETE, etc.
you can get more information for express-validator and validate methods in : https://express-validator.github.io/docs/
so lets create ./api/index.js
like below :
as you can see in this we response with .get()
to get and .post()
for post method
in normal next.js we had to use something like :
but in next-connect its become easier to use just use :
.post(async(req,res)=>{
doSomething()
return res.json({success : true})
})
4- test your app
type npm run dev
or npm run build && npm run start
to test your API validation first we attempt to get
request via postman
:
now change method to post with username
and password
body :
as you can see its works! but when we miss password
it have to response an error that we define in step 3 so lets check it :
we got error! and if we missed username
message our message will be added in error
array