Generating sitemap.xml with i18n support in Next.js
i18n support
Yesterday, I added i18n (internationalization) setting to this blog. i18n is officially supported by Next.js, and all you have to do is write the appropriate settings in next.config.js
. There is a lot of information about this on the internet, so I won't go into it in this article. In this article, I'd like to write about modifications required for sitemap generation to support i18n. The following story assumes that the application is deployed to Vercel. The version of Next.js at the time of writing is 12.0.1
.
Sitemap generation
Before i18n support
The following library is used to generate sitemap for this blog.
https://www.npmjs.com/package/next-sitemap
If you use this library, you can generate sitemap.xml by defining sitemap.config.js
and modifying the build script a little. Before i18n support, this blog's sitemap.config.js
and build script was as follows.
sitemap.config.jsmodule.exports = {
siteUrl: 'https://silurus.dev',
generateRobotsTxt: true,
sitemapSize: 7000,
outDir: '. /out'
};
````json:package.json
```json:package.json
"scripts": {
"build": "next build && next export && next-sitemap --config sitemap.config.js",
},
With the above configuration, sitemap could be accessed with https://silurus.dev/sitemap.xml.
After i18n support
After adding i18n settings in Next.js project, next export
is not available, so you need to modify the build script of package.json
as follows.
package.json"scripts": {
"build": "next build && next-sitemap --config sitemap.config.js",
},
Then, in sitemap.config.js
, outDir: '. /out'
is inconsistent. The out
directory is a directory created as a result of next export
, so the directory does not exist in next build
alone. If this is the case, sitemap.xml will not be included in static resources after deployment on Vercel, and it will not be accessible with the original URL.
So, you need to modify sitemap.config.js
as follows.
sitemap.config.jsmodule.exports = {
siteUrl: 'https://silurus.dev',
generateRobotsTxt: true,
sitemapSize: 7000,
outDir: '. /public'; }
};
If you put it in the public
folder, you can access it with the base path/file name
after the build, so you can continue to access it with the same address.
In the case of this site, you can access to sitemap with the original address: https://silurus.dev/sitemap.xml