Ways to display a different landing page when navigating to the homepage of a website

In the Next application, I have set up a dynamic route at the root of my pages folder as src/pages/[page].js

While this works smoothly for pages with slugs like example.com/my-page, it poses a challenge when trying to access a designated slug named homepage for the main website page at example.com.

Is there a solution to enable accessing a specific slug like homepage for the root of the website? Below is a simplified version of my component:

import React from "react";
import { fetchAPI } from "../lib/api";

const Page = () => <p>Content...</p>;

export default Page;

export async function getStaticPaths() {
  const pages = await fetchAPI("/pages");
  return {
    paths: pages.map((page) => ({
      params: {
        page: page.slug,
      },
    })),
    fallback: false,
  };
}

export async function getStaticProps({ params }) {
  const pages = await fetchAPI(`/pages?slug=${params.page}`);
  return {
    props: { page: pages[0] },
    revalidate: 1,
  };
}

Answer №1

If you want to redirect the / path to a different destination like /homepage, you can set up rewrites in the next.config.js file. This configuration will ensure that the URL displayed in the address bar remains unchanged.

// next.config.js
module.exports = {
    async rewrites() {
        return [
            {
                source: '/',
                destination: '/homepage'
            }
        ];
    }
};

By using this method, you can easily manage your route redirects within Next.js.

Answer №2

When using getStaticProps, it's important to note that on the home page, your params.page will be undefined due to the dynamic route setup. To handle this scenario, you can make a simple adjustment:

export async function getStaticProps({ params }) {
  const pageSlug = params.page ?? "homepage"
  const pages = await fetchAPI(`/pages?slug=${pageSlug}`);
  return {
    props: { page: pages[0] },
    revalidate: 1,
  };
}

Solution for Redirecting 404 Pages to Homepage

In response to a comment expressing concerns about displaying the homepage instead of a 404 error page when accessing non-existent URLs, there are several approaches you can consider:

Redirecting to Homepage on 404 (Recommended)

You can implement a redirect to the homepage if the requested page is not found in your pages data. This method is preferred as it avoids duplicate content issues and unnecessary processing:

export async function getStaticProps({ params }) {
  const pageSlug = params.page ?? "homepage"
  const pages = await fetchAPI(`/pages?slug=${pageSlug}`);
  if(!pages || !pages.length > 0) {
    return {
      redirect: {
        destination: '/',
        permanent: false,
      },
    }
  }
  return {
    props: { page: pages[0] },
    revalidate: 1,
  };
}

The recommended approach ensures a smooth user experience without compromising SEO performance.

Using 404.js (or 404.tsx) for Redirection

Create a custom 404 page file like 404.js or 404.tsx which Next.js utilizes when encountering a 404 error. You can leverage the getStaticProps function to redirect to the homepage:

// 404.js
export default function FourOhFourPage() {
  return null
}

export async function getStaticProps({ params }) {
  return {
    redirect: {
      destination: '/',
      permanent: false,
    },
  };
}
Displaying Home Page Content for Any 404 URL

An alternative approach involves querying the API for the homepage content if no valid page is found initially. While this may result in an additional API call, it can be managed by setting up canonical URLs to avoid SEO penalties:

export async function getStaticProps({ params }) {
  const pageSlug = params.page ?? "homepage"
  let pages = await fetchAPI(`/pages?slug=${pageSlug}`);
  if(!pages || !pages.length > 0) {
    pages = await fetchAPI(`/pages?slug=homepage`);
  }
  return {
    props: { page: pages[0] },
    revalidate: 1,
  };
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating an Angular form that adapts to changing input values

I'm encountering a problem with angular not recognizing the dynamic values from my inputs. My objective is to have angular populate hidden form fields with lat/lon when a user clicks on the map. The user then submits the form, but the data ends up mi ...

React ES6 SystemJS encountered an unforeseen token error that couldn't be caught

Even though I have imported react and react-dom using the System.config setup below, I am still encountering the error mentioned here: Uncaught (in promise) Error: Unexpected token <(…) Here is the HTML structure: <!DOCTYPE html> <html l ...

Incorporating jQuery ajax requests into divs seamlessly to avoid any page disruptions

When loading numerous ajax calls on a page, the timing of each call varies, resulting in some content loading before the user reaches the top of the page. This may cause the user to miss viewing certain data unless they scroll back up to the top. Below is ...

Ways to remove a

After creating an npm link within a local dependency and then deleting that dependency from my hard drive, I am now attempting to remove this npm link. I have attempted the following steps: npm rm --global dependency npm uninstall dependency npm unlink - ...

Is it necessary for the scope to be separated?

In the document object model (DOM), I have two straightforward directives that are responsible for creating similar elements. Both directives have an isolated scope. Each directive has an ng-click attribute that calls a method to display a message. One d ...

Creating a unique texture on a spherical object using THREE.js

Can a sphere be textured in sections rather than all at once? Just like we can use 6 textures on 6 sides of a cube, is it possible to apply different textures to different parts of a sphere? For example, dividing the sphere into quarters and texturing each ...

Guide on making a button display an image, then switch back to the initial image when clicked again

Currently, I have this neat feature on my website where there's a button that toggles the image/background color - kind of like a dark mode switch. The background change is working fine, but I'm encountering some challenges with organizing the im ...

Is Riot.js the best choice for server-side rendering and routing?

Currently, I am using Node along with Riot.js and the Grapnel routing library. I have successfully set up routing on the client side, but I am facing difficulty in making it work on the server side. The functioning of my client router is straightforward. ...

Combine an array of objects using the main key in each object

I have an array of objects with different years and details var worksSummaryDetailsArr = [ { year: 2020, worksSummaryDetailsObj: [ [Object], [Object], [Object], [Object] ] }, { year: 2021, worksSummaryDetailsObj: [ [Object], [Object], ...

I. Discovering the Step-by-Step Guide on Retrieving User Information from Facebook Upon Generating App

I have set up a Facebook login for user registration on my website. However, I am only able to retrieve the profile name and user ID from Facebook. How can I access the email and other user information? Here is the data I am currently receiving from Faceb ...

Why do variables maintain the same value across modules when using the require function in Node.js?

We have a scenario where we have multiple files in the same directory: data.js var anArray = [1,2]; module.exports = anArray; mod1.js var data = require('./data'); module.exports = data; mod2.js var data = require('./data'); modul ...

Using HTML and CSS to create interactive icons that change color when clicked, similar to how a link behaves

Have you ever wondered if there's a way to make an icon act like a link when clicked, just like regular text links turning purple? And not just the last one clicked, but every single icon that gets clicked. Trying to use the :visited pseudo was unsucc ...

Trouble displaying JSON data when using a search box filter in React

My webpage is using JSON dummy data that can be filtered by keywords entered into a search box. Previously, all the data displayed correctly before creating filteredJson, but now nothing is showing up. What could be causing this issue? I want to send the ...

Can a `react` app with `mysql` be uploaded to `github`?

I recently created a basic online store with the help of react, node, and mysql. I am considering uploading it to github, but I'm uncertain if I can do so while my database is currently stored on localhost. Any advice? ...

Converting text into HTML format using Nextjs and React

Currently, I am working on a project that involves using Next.js and React. I am considering creating my own component to parse text based on certain conditions, but I am unsure if something similar already exists. My goal is to: Format the content in HT ...

Stopping Form Submission with MUI TextField

I am currently creating a form using React along with MUI. I'm trying to figure out how to prevent the form from being submitted when the user hits the enter key. Usually, I would use e.preventDefault(), but for some reason it's not working in th ...

Leveraging Vue.js to showcase API information through attribute binding

My application is designed to allow a user to select a Person, and then Vue makes an API call for that user's posts. Each post has its own set of comments sourced from here. You can view the codepen here Here is my HTML structure: <script src="h ...

Automated vertical alignment of rows within the Bootstrap table

I'm currently working on a table for my personal project that populates with data from the database. I am trying to get the rows to display vertically under headings (see screenshot at the bottom of this question). I have attempted various solutions f ...

Is Python a suitable programming language for developing applications on a Raspberry Pi device?

I'm diving into the coding world for the first time and I have a project in mind - controlling my RC car with my smartphone using a Raspberry Pi 3. Research suggests that I should use Node.JS and JavaScript to create the app, but I'm wondering if ...

Getting a list of connected users on a PeerJS server using Express is simple and straightforward. Follow these steps to

Trying to incorporate PeerJS, a webRTC library, into a game and utilizing their server for user discovery has proven challenging. The goal is to manage a list of connected users, but grappling with the PeerJS server has been difficult. The documentation s ...