From 90fe39b3f5b618132bfc13117e0c188638691197 Mon Sep 17 00:00:00 2001 From: Alex Tkachev Date: Mon, 25 Sep 2023 17:51:56 +0400 Subject: [PATCH] feat: add lang attribute to html tag --- apps/website/gatsby-ssr.ts | 27 +++++++++++++++++++++++++++ tests/e2e/specs/metatags.spec.ts | 12 ++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 apps/website/gatsby-ssr.ts diff --git a/apps/website/gatsby-ssr.ts b/apps/website/gatsby-ssr.ts new file mode 100644 index 000000000..375c350ba --- /dev/null +++ b/apps/website/gatsby-ssr.ts @@ -0,0 +1,27 @@ +import './styles.css'; + +import { Locale } from '@custom/schema'; +import { GatsbySSR } from 'gatsby'; + +export const onRenderBody: GatsbySSR['onRenderBody'] = ({ + setHtmlAttributes, + pathname, +}) => { + const locales = Object.values(Locale); + if (locales.length === 1) { + // Single-language project. + setHtmlAttributes({ + lang: locales[0], + }); + } else { + // Multi-language project. + const prefix = pathname.split('/')[1]; + if (locales.includes(prefix as Locale)) { + setHtmlAttributes({ + lang: prefix, + }); + } else { + // We don't know the language. + } + } +}; diff --git a/tests/e2e/specs/metatags.spec.ts b/tests/e2e/specs/metatags.spec.ts index 4dd202bae..32f922085 100644 --- a/tests/e2e/specs/metatags.spec.ts +++ b/tests/e2e/specs/metatags.spec.ts @@ -18,3 +18,15 @@ test('Metatags on Basic page', async ({ page }) => { pageUrl, ); }); + +test('HTML lang attribute', async ({ page }) => { + await page.goto(websiteUrl('/en')); + await expect(page.locator('html')).toHaveAttribute('lang', 'en'); + await page.goto(websiteUrl('/de')); + await expect(page.locator('html')).toHaveAttribute('lang', 'de'); + + await page.goto(websiteUrl('/en/imprint')); + await expect(page.locator('html')).toHaveAttribute('lang', 'en'); + await page.goto(websiteUrl('/de/impressum')); + await expect(page.locator('html')).toHaveAttribute('lang', 'de'); +});