DEV Community

Discussion on: Use middleware in Next.js without custom server

Collapse
 
hoangvvo profile image
Hoang

One tip: If you want several middleware to be available on every page. Create a file (say, withMiddleware.js).

This will apply to approach 1.

// withMiddleware.js

import thisMiddleware from './thisMiddleware.js'
import thatMiddleware from './thatMiddleware.js'

const withMiddleware = handler => thisMiddleware(thatMiddleware(handler));

export default handler;

Then wrap whatever you need with withMiddleware.

Approach 2, similar thing:

import thisMiddleware from './thisMiddleware.js'
import thatMiddleware from './thatMiddleware.js'

const useMiddleware = async (req, res) => {
  await thisMiddleware(req, res);
  await thatMiddleware(req, res);
}

export default useMiddleware
Collapse
 
robbiegm profile image
RobbieGM • Edited

Why not just export the handler with middleware already applied to it? From the docs it seems like that's the recommended way to do it.