Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Here's an example of how to create a Next.js middleware matcher that targets URLs containing capital letters:

const matchCapitalLetters = (req, res, next) => {
  if (/[A-Z]/.test(req.url)) {
    // request URL contains capital letters
    console.log('Matched a URL with capital letters:', req.url);
    // your middleware logic here
  } else {
    // request URL doesn't contain capital letters
    next();
  }
}

export default matchCapitalLetters;

This middleware function uses a regular expression to test whether the requested URL contains any capital letters. If it does, the middleware logs a message and executes your custom logic. Otherwise, it passes the request to the next middleware in the chain using next().

To use this middleware in your Next.js application, simply import it and add it to your custom server.js file as shown below:

const express = require('express');
const next = require('next');
const matchCapitalLetters = require('./matchCapitalLetters');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.use(matchCapitalLetters);

  server.get('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(3000, (err) => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});

Note that this middleware will only match URLs that contain at least one capital letter. To match all URLs that have a capital letter anywhere in the URL string, you could replace the regular expression with /[a-z].*[A-Z].*/.