Reputation: 2939
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?
Upvotes: 11
Views: 10173
Reputation: 396
In your public
folder you can create a folder structure patterned after the URL you want.
For example:
public/custom-path-folder-name/file.html
will be served at:
http://localhost:3000/custom-path-folder-name/file.html
For more information see the nextjs docs for static file serving
Upvotes: 5
Reputation: 1243
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.
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
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();
}
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>'},
],
};
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.
Upvotes: 8