0
0
NextJSframework~15 mins

Redirect function in NextJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Redirect Function in Next.js
📖 Scenario: You are building a simple Next.js app where users can be redirected from one page to another based on a condition.
🎯 Goal: Create a Next.js page that redirects users to a different URL using the redirect function from Next.js.
📋 What You'll Learn
Create a Next.js page component
Use the redirect function from next/navigation
Set up a condition to trigger the redirect
Export the page as a default React component
💡 Why This Matters
🌍 Real World
Redirects are common in web apps to send users to login pages, error pages, or updated content automatically.
💼 Career
Understanding how to use Next.js redirect functions is important for building user-friendly navigation flows in modern web applications.
Progress0 / 4 steps
1
Create a Next.js page component
Create a new file called page.tsx and write a React functional component named Page that returns a simple <div> with the text Welcome to the redirect demo.
NextJS
Need a hint?

Start by defining a function named Page that returns a <div> with the welcome text.

2
Import the redirect function
At the top of page.tsx, import the redirect function from next/navigation.
NextJS
Need a hint?

Use the ES module import syntax to import redirect from next/navigation.

3
Add a condition to trigger redirect
Inside the Page component, create a constant named shouldRedirect and set it to true. Then, add an if statement that calls redirect('/new-page') if shouldRedirect is true.
NextJS
Need a hint?

Use a simple if statement to check shouldRedirect and call redirect with the target path.

4
Complete the redirect page
Ensure the Page component exports as default and the redirect logic is correctly placed before the return statement.
NextJS
Need a hint?

Make sure the redirect happens before the component returns JSX.