How to redirect to another page if user gets to a specific url in next.js?

by dalton_moen , in category: Third Party Scripts , 2 months ago

How to redirect to another page if user gets to a specific url in next.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lew , 2 months ago

@dalton_moen 

In Next.js, you can use the getServerSideProps function to check if the user has accessed a specific URL and then redirect them to another page. Here's an example of how you can achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// pages/specific-page.js

import { useRouter } from 'next/router';

export default function SpecificPage({ someData }) {
  const router = useRouter();

  // Check if user has accessed a specific URL
  if (someData !== 'expectedValue') {
    // Redirect to another page
    router.push('/another-page');
  }

  return (
    <div>
      <h1>This is the specific page</h1>
    </div>
  )
}

export async function getServerSideProps() {
  // Perform some logic to check if user has accessed specific URL
  const someData = 'value';

  return {
    props: {
      someData
    }
  }
}


In the getServerSideProps function, you can perform any logic to determine if the user has accessed the specific URL. If the condition is met, you can return the data as props. In the component, you can then use the useRouter hook to check the value of someData and redirect the user to another page if necessary.


Note: Make sure to import useRouter from 'next/router' at the beginning of the component file.