0

Is it possible to conditionally redirect based on the referrer of the visitor?

What I want to do is redirecting the user if it comes from a specific domain (and/or any other subdomains), if there is no referrer or the domain does not match, no redirection should apply.

I was thinking using getServerSideProps().

FFF
  • 13
  • 7

1 Answers1

1

Such logic reading headers needs to be on some server and you should be able to read the referrer in the middleware where you can handle redirects too. This should work in theory:

// pages/_middleware.ts
import type { NextRequest, NextResponse } from 'next/server';

export function middleware(req: NextRequest) {
  console.log('referrer', req.referrer); // do your domain parsing / regex here

  // redirect with NextResponse.redirect()
}

There are inherent limits in reliability of the referrer as the value might be opaque to you.

I'd question the use case of such source sniffing and conditional redirects in first place.

dmudro
  • 2,894
  • 1
  • 21
  • 23