How to Change Home Page to Use a Different File in NextJS

Jasser Mark Arioste

Hello hustler. In this short tutorial, you'll learn how to change the home page to point to another file in a NextJS Application. Learn how to go around the file-based routing of NextJS.
The Problem #
I had one requirement once in my project and the /index route is different from the / route. The problem is NextJS uses file-based routing and it automatically uses index.tsx as the home(/) route.
The Solution #
To implement this requirement, I did the following:
- Remove the
index.tsxfile from the/pagesdirectory, so that NextJS will not see a home page route. - Create a file
pages/home.tsxfor the / route. - Create a file
pages/my-index.tsxfor the /index route. - Use
rewritesandredirectsinsidenext.config.jsto wire up the routing.
After the first three steps, the folder structure will look like this:
|- /pages |- home.tsx |- my-index.tsx |- _app.tsx |- tsconfig.json |- package.json |- next.config.js123456
Since we don't have the pages/index.tsx file, navigating to / will return us the 404 page:

To fix this, let's use rewrites() in next.config.js to point the routes to the correct files. Rewrites allow you to map an incoming request path to a different destination path.
// next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, swcMinify: true, async rewrites() { return [ { source: "/", destination: "/home", }, { source: "/index", destination: "/_index", }, ]; }, }; module.exports = nextConfig;1234567891011121314151617181920
After changing next.config.js, restart your local server.
Now, navigating to / and /index routes should render correctly:


Next, let's prevent users from accessing /home and /my-index routes. Use redirects() in next.config.js to redirect /home and /my-index to the correct destination:
// next.config.js /** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true, swcMinify: true, ... async redirects() { return [ { source: "/home", destination: "/", statusCode: 301, }, { source: "/my-index", destination: "/index", statusCode: 301, }, ]; }, }; module.exports = nextConfig;1234567891011121314151617181920212223
Now navigating to /home will redirect to / and navigating to /my-index will redirect to /index.
Conclusion #
Although file-based routing is great in NextJS, it still has some limitations. Rewrites and Redirects are incredibly powerful when used correctly and it allows us to work around the limitations of file-based routing.
If you like this tutorial, please leave a like or share this article. For future tutorials like this, please subscribe to our newsletter or follow me on Twitter.
Resources #
Related Posts #
Credits: Image by Eiji Kikuta from Pixabay






