Hendry Lim
Hendry Lim

Reputation: 1974

Apply Middleware for specific next-connect routes among other routes in same file

I am using next-connect and like to apply a yup validation middleware for a specific route only (post). The file which contains the route also contains other routes (eg get, put). Is there anyway I can apply the yup validation middleware on my post route only? or this file can only contain my post route whilst my other api routes like get and put will need to be saved in another file?

Below are the codes... appreciate advise, thanks

import nextConnect from "next-connect";
import bcrypt from "bcryptjs";

import middleware from "../../middlewares/middleware";
import yupValidator from "../../middlewares/yupValidator";
import { extractUser } from "../../lib/api-helpers";

const handler = nextConnect();

//! For Global Middlewares
handler.use(middleware);

handler
  .post(async (req, res) => {
    //! Apply yupValidator for this route only
    const { name, password } = req.body;
    console.log(name, body);
  })
  .get(async (req, res) => {
    //! Do not apply yupValidator for this route
    console.log(req);
  });

Upvotes: 1

Views: 1634

Answers (2)

Rishab Sharma
Rishab Sharma

Reputation: 91

We can use next-connect just like express

Codesandbox link - codesandbox

Define handler

const handler = nc(); 

For Global Middlewares use

handler.use(middleware1, middleware2, middleware3, ....);

For Method Specific Middlewares

As per next-connect documentation, methods (get, post, put, delete) in next-connect accept an array of handlers, so we can pass bunch of functions as middleware to any method which takes 3 arguments req, res and next (if you're using ts then it's type is NextHandler) just like any other middleware.

Example

handler.get(
    getLevelMiddleware1,
    getLevelMiddleware2,
    ...
    ...
    (req, res) => {
        res.send("GET METHOD");
    }
); // get method specific middleware
handler.post(
    postLevelMiddleware1,
    postLevelMiddleware2,
    ...
    ...
    (req, res) => {
        res.send("POST METHOD");
    }
); // post method specific middleware

Example Middleware

// ignore type annotations if you're using JS
const exampleMiddleware = (
    req: NextApiRequest,
    res: NextApiResponse,
    next: NextHandler
) => {
    console.log("Example middleware.");
    next();
};

And at the end just export default handler

Upvotes: 0

Hendry Lim
Hendry Lim

Reputation: 1974

import nc from "next-connect";
import bcrypt from "bcryptjs";
import * as yup from "yup";

import middleware from "../../middlewares/middleware";
import yupValidator from "../../middlewares/yupValidator";
import { extractUser } from "../../lib/api-helpers";

const userSchema = yup.object().shape({
  name: yup.string().trim().required().min(3),
  password: yup.string().required().min(5, "must be more than 5 words la"),
});

const handler = nc();

//! For Global Middlewares
const base = nc().use(middleware);
//! Route Specific Middlewares
const validation = nc().post("/api/users", yupValidator(userSchema));

handler
  .use(base)
  .use(validation)
  .post(async (req, res) => {
    //! Apply yupValidator for this route only
    const { name, password } = req.body;
    console.log(name, password);
    res.status(201).send("Done");
  })
  .get(async (req, res) => {
    //! yupValidator not applied to this get route
    console.log(req);
  })
  .put(async (req, res) => {
    //! yupValidator not applied to this put route
    const { name, password } = req.body;
    console.log(name, password);
    res.status(201).send("Done");
  });

export default handler;

Upvotes: 1

Related Questions