Foobar
Foobar

Reputation: 8487

Serve top level domain as static html page in next.js?

In next.js you can use the "public" directory in your root directory to serve static assets. I have my index.html file in this directory because I want my landing page to be purely static.

However, when using next or next start, I cannot access my landing page at http://localhost:3000/. I can only access my landing page at "http://localhost:3000/index.html".

Is there a way to setup next.js, so the top level domain (http://localhost:3000) will serve my landing page?

Upvotes: 6

Views: 5976

Answers (2)

Bob
Bob

Reputation: 1095

You can add rewrites to your next.config.js. To allow the url mysite.com/ to point to /public/index.html, I added this to my config (with the content in my /public directory):

rewrites: async () => {
    return [
      {
        source: "/",
        destination: "/index.html",
      }
    ]
}

Note: index.jsx/.tsx will take precedence over files in /public

Source: https://nextjs.org/docs/api-reference/next.config.js/rewrites

Upvotes: 5

Nikolai Kiselev
Nikolai Kiselev

Reputation: 6613

Next.js router serves only pages exported from .js, .ts and .tsx in pages directory.

You would need a custom server that would serve anything outside of that.

Custom Server

Also, if you use a reverse proxy like nginx you could handle this request by the server before it hits Node.js.

What is the use case of it? If the landing page is just a .html file, you can wrap it in a Next.js page. With server side rendering, the page will be pre-rendered on the server and served the same as it was just a .html file.

Alternatively, if you can't convert HTML to JSX you could use dangerouslySetInnerHTML to set raw HTML code to React's render(). However, beware of cross-site scripting (XSS) attacks.

Upvotes: 1

Related Questions