Comments (5)
I never used next-sitemap. I gave a quick look to the readme, and if I understand correctly you want to leverage the transform function to translate the path...
The path you get should be the file path prefixed by the locale : translateUrl
handle this.
If you succeed to make it work, please open a pull request here to add the correct config to the readme !
from next-translate-routes.
You could try the following; create sitemap.xml.tsx
within your pages folder with the following content:
import type { GetServerSideProps, GetServerSidePropsContext } from 'next';
import * as React from 'react';
import fs from 'fs';
import { translateUrl } from 'next-translate-routes';
export default function Sitemap() {
return null;
};
export const getServerSideProps: GetServerSideProps = async (props: GetServerSidePropsContext) => {
const { res, locales, defaultLocale } = props;
const url = `${process.env.PROJECT_URL?.replace(/\/+$/, '')}`;
const ourLocales = (Array.isArray(locales) ? locales : [defaultLocale || 'en']);
// Get static paths.
const pagesDirectory = fs.readdirSync('src/pages');
const pages = pagesDirectory
.filter(page => page.match(/.*\.(tsx?)/ig))
.filter(page => !['_app.tsx', '_document.tsx', '_error.tsx', 'sitemap.xml.tsx'].includes(page))
.map(page => page.replace('.tsx', ''));
let paths = pages.map(page => ourLocales.map(locale => ({
locale,
path: `${url}${translateUrl(page, locale)}`,
})));
// Get dynamic paths.
try {
const yourDynamicRequestedPaths: Something[] = await yourAPIRequest();
paths = [
...paths,
...yourDynamicRequestedPaths,
];
} catch (error) {
}
const entries = paths.map((entry) => `
<url>
<loc>${entry.find(path => path.locale === (defaultLocale || 'en'))?.path}</loc>
<lastmod>${new Date().toISOString()}</lastmod>
<changefreq>monthly</changefreq>
<priority>1.0</priority>
${entry.map(path => `<xhtml:link rel="alternate" hreflang="${path.locale}" href="${path.path}"/>`).join('')}
</url>
`).join('');
const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
<urlset
xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
xmlns:xhtml="http://www.w3.org/1999/xhtml" >
${entries}
</urlset>`;
res.setHeader('Content-Type', 'text/xml');
res.write(sitemap);
res.end();
return {
props: {},
};
};
from next-translate-routes.
This is how I got it working
/** @type {import('next-sitemap').IConfig} */
const path = require('path');
const { translateUrl } = require('next-translate-routes');
const { createNtrData } = require('next-translate-routes/plugin');
const nextConfig = require('./next.config');
const i18NextConfig = require('./next-i18next.config');
const data = createNtrData(
nextConfig,
path.resolve(process.cwd(), './src/pages')
);
global.__NEXT_TRANSLATE_ROUTES_DATA = data;
module.exports = {
siteUrl: process.env.SITE_URL,
generateRobotsTxt: true, // (optional)
// ...other options
transform: async (config, path) => {
const locale =
i18NextConfig.i18n.locales.find(
(locale) => path.indexOf(`/${locale}/`) > -1
) || i18NextConfig.i18n.defaultLocale;
return {
loc: translateUrl(path, locale), // => this will be exported as http(s)://<config.siteUrl>/<path>
changefreq: config.changefreq,
priority: config.priority,
lastmod: config.autoLastmod ? new Date().toISOString() : undefined,
alternateRefs: config.alternateRefs ?? [],
};
},
};
from next-translate-routes.
I linked toward @JacobSoderblom's suggestion in the docs.
from next-translate-routes.
If someone is is wondering how to add alternateRefs for each language, here's how I got it working
/** @type {import('next-sitemap').IConfig} */
module.exports = {
siteUrl: process.env.NEXT_PUBLIC_SITE_URL,
generateRobotsTxt: true,
transform: (config, path) => {
const locale = i18NextConfig.i18n.locales.find((locale) => path.includes(`/${locale}`));
const fileUrl = urlToFileUrl(path, locale || i18NextConfig.i18n.defaultLocale);
return {
loc: translateUrl(path, locale || i18NextConfig.i18n.defaultLocale),
changefreq: config.changefreq,
priority: config.priority,
lastmod: config.autoLastmod ? new Date().toISOString() : undefined,
alternateRefs: fileUrl
? i18NextConfig.i18n.locales.map((locale) => ({
href: `${process.env.NEXT_PUBLIC_SITE_URL}${fileUrlToUrl(fileUrl, locale)}`,
hreflang: locale,
hrefIsAbsolute: true,
}))
: [],
};
},
};
from next-translate-routes.
Related Issues (20)
- 1.9.0-3 - navigation to wrong translation reloads the app HOT 1
- Trans component doesn't seem to work in this example HOT 1
- Plugin can't be used with @sentry/nextjs HOT 2
- Route using translated locale/.json file HOT 16
- Can't install the latest version v1.9.0 with yarn HOT 1
- Does this plugin support locale format en-US, es-MX, etc? HOT 2
- Add Next 13 support HOT 3
- Typescript support for Link properties HOT 1
- Link to dynamic route results in ERR_ABORTED 404 (Not Found), then redirects correctly HOT 2
- Incorrect translation of external links HOT 4
- How to use next-translate-routes with I18next and withPlugins? HOT 1
- [storybook] - No wrapped App component in withTranslateRoutes HOT 1
- Support for fallback / substituable language (nonExplicitSupportedLngs) HOT 9
- We support Dynamic Routes and getStaticProps Pages from next.js? HOT 9
- fileUrlToUrl breaks on 404 HOT 2
- Add support for Next 13 `/app` directory HOT 4
- Update LinkProps to support Next.js 13 <Link> component HOT 2
- Update pagesDirs to support Next.js 11 pages path HOT 1
- Next Link supports ref, but next-translate-routes does not HOT 1
- Routing does not work any more after update to next 13.3.0 HOT 7
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from next-translate-routes.