Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

525
Views
Middleware for each route server side in Next.js

I'm trying to figure out a way to have some code run on initial page load for each request. I want to be able to identify the request domain and redirect to a specific part of the website based on it.

From what I can understand I could add getInitialProps to a custom _app page but that would disable all optimization from next. Also _app doesn't seem to support getServerSideProps which I considered as an alternative.

Another way I thought about doing it was to have getServerSideProps in each page of the website with the check I have to do, but this would make every page rerender on server side for each new request, disabling rendering at build time even for pure static pages.

Is there any other solution I can adopt?

EDIT

Basically I need the request object so that I can do something like this:

export const getServerSideProps: GetServerSideProps = async ({
  req
}) => {
  if (req.headers.host === 'something') {
     return {
       redirect: {
         permanent: false,
         destination: "/"
       }
     }
  }
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

I would put solutions to this in the order below:

  1. do redirect on your server(nginx or something), fastest solution
  2. you could create custom [Next.js server][1] to handle redirect
  3. custom App as you said
  4. RouteGuard used in each page which would redirect
about 4 years ago · Juan Pablo Isaza Report

0

You can use Next.js redirects in your next.config.js file.

module.exports = {
    async redirects() {
        return [
            {
                source: '/(.+)',
                has: [
                    {
                        type: 'header',
                        key: 'host',
                        value: 'something'
                    }
                ],
                permanent: false,
                destination: '/'
            }
        ]
    }
}

This rule will match any path that's not /, and redirect if it contains the desired host header value.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!