Setting up the home page on Next.js

Viewed 13025

Does anybody know how to define any specific page in Next.js as the root (the home page)?

I have been looking online and was not able to find any concrete solutions. This is suppose to be a very common use case.

There is this other post, Using Next.js next-routes, how to define a home route for the base web page?, but it recommends creating a server for it.

It there any "NextJs" way of setting up a Home Page?

Any thoughts?

Thanks in advance!

3 Answers

“When a file is added to the pages directory it's automatically available as a route.

The files inside the pages directory can be used to define most common patterns.”

The router will automatically route files named index to the root of the directory.

pages/index.js/

More details: https://nextjs.org/docs/routing/introduction

I posted the answer that solved my issue in this other thread:

Next.js Redirect from / to another page

The example was taken from https://dev.to/justincy/client-side-and-server-side-redirection-in-next-js-3ile

I needed to immediately forward the user who visited my root page (mywebsite.com/) to a subpage, in this case Home: mywebsite.com/home

Pasting either of the following in my main index.js file, achieves the desired result:

There are copy-paste-level examples for

Client Side

import { useRouter } from 'next/router'

function RedirectPage() {
  const router = useRouter()
  // Make sure we're in the browser
  if (typeof window !== 'undefined') {
    router.push('/home')
  }
}

export default RedirectPage

Server Side

import { useRouter } from 'next/router'

function RedirectPage({ ctx }) {
  const router = useRouter()
  // Make sure we're in the browser
  if (typeof window !== 'undefined') {
    router.push('/home');
    return; 
  }
}

RedirectPage.getInitialProps = ctx => {
  // We check for ctx.res to make sure we're on the server.
  if (ctx.res) {
    ctx.res.writeHead(302, { Location: '/home' });
    ctx.res.end();
  }
  return { };
}

export default RedirectPage
Related