Search code examples
reactjsnext.jsnext-router

How to server a ".html" at certain URL in a Next.js app?


I have an ".html" file that I need to serve in a certain route in my Next.js app, like this ...

/pages/customr-route-name/my-html-file.html

So if I go to my website and type http://example.com/custom-route-name/my-html-file.html I can see it

How can I do that in Next.js?


Solution

  • This one requires an API route and a URL rewrite to get working. And the nice thing is, you'll be able to use this pattern for other things too (like if you want to generate an RSS feed or a sitemap.xml).

    NOTE: You will need to be running Next 9.5 for this to work.

    0. Move your HTML file (Optional)

    Your file doesn't need to be located in the ./pages dir. Let's put it in ./static instead. Just replace your these route-file placeholders with your real filename later: ./static/<route>/<file>.html

    1. Create the API route

    Next lets you create API routes similar to how you would in an old-style host like Express. Any name is fine as long as it's in ./pages/api. We'll call it ./pages/api/static/<route>/<file>.js

    // import
    
    import fs from 'fs';
    
    // vars
    
    const filename = './static/<route>/<file>.html';
    
    // export
    
    export default async function api(req, res) {
      res.setHeader('Content-Type', 'text/html; charset=utf-8');
      res.write(await fs.readFileSync(filename, 'utf-8'));
      res.end();
    }
    
    

    2. Add a rewrite to next.config.js

    In Next, rewrites work similar to their apache counterparts. They map a url location to a Next ./page.

    // export
    
    module.exports = {
      rewrites: async () => [
        {source: '/<route>/<file>', destination: './pages/api/static/<route>/<file>'},
      ],
    };
    

    3. Run it!

    You should be able to test this with a regular next dev. Of course, changes to next.config.js require you to manually reboot the dev server.

    If you look at the Next docs, you'll see you can use wildcards in both the API routes and these redirects, which might help with the direction you're going.