Making a Portfolio Bilingual: React i18n Without a Library
Build a Developer Portfolio · Part 9 of 9
- #Portfolio
- #personal-website
- #i18n
- #react
- #typescript
Adding a second language to a portfolio sounds like a job for a library. For a lot of sites it isn't. If you have two languages, a hundred or so UI strings and content written in Markdown, you can do React i18n without a library in a few small files you fully understand, and have TypeScript refuse to build when a translation is missing.
This site works that way. English is the default and lives at unprefixed
URLs (/blog); Portuguese lives under /pt-br (/pt-br/blog). The whole
layer is a config file, one context provider, two dictionaries and a
cookie helper. This post goes through each piece, the SEO side
(hreflang, canonicals, the sitemap), what happens when a post exists in
only one language, and the point where you should stop hand-rolling and
install react-i18next or Lingui instead.
It's the last part of the series. Part 8 covered metadata and sitemaps for a single language; this one adds the second.
Do you actually need an i18n library?
Libraries like react-i18next, Lingui and FormatJS solve real problems. The question is whether you have those problems yet.
On this site, en.ts holds 105 strings in 13 sections (nav, footer, home,
about, blog, and so on). There are two languages, both maintained by the
same person who writes the code. Blog posts are Markdown files, not
strings. Nothing needs gendered forms, and the only number shown next to a
word is a reading time ("5 min read"), which doesn't change with the
count.
At that size, a library mostly adds things you won't use: a runtime, a configuration file, a key-extraction step, and an extra layer between you and a string you could just open and read. What you do need is smaller:
- a reliable way to know which language the page is in,
- strings that can't silently go missing in one language,
- links that stay in the current language,
- and correct signals to search engines about which page is which.
None of that needs a dependency. The last section of this post lists what would change the answer.
The URL decides the language
The most important decision comes before any code: the language is
part of the URL. Not React state, not localStorage, not the browser's
Accept-Language header.
A URL is something you can share, bookmark and get indexed. If
/blog/some-post could render in either language depending on who asks,
a recruiter in São Paulo and one in Berlin would see different pages at
the same address, and search engines would only ever index one of them.
Google's own guidance for multilingual sites is to give each language its
own URL, and that's what this site does.
The rules fit in one file. The default locale has no prefix, Portuguese
gets /pt-br, and a few helpers convert between the two:
export type Locale = 'en' | 'pt-BR';
const LOCALE_PREFIX: Record<Locale, string> = {
en: '',
'pt-BR': '/pt-br',
};
/** Locale implied by a pathname, e.g. `/pt-br/blog` -> `pt-BR`. */
export function localeFromPathname(pathname: string): Locale {
return pathname === '/pt-br' || pathname.startsWith('/pt-br/')
? 'pt-BR'
: 'en';
}
/** Strip the locale prefix, e.g. `/pt-br/blog` -> `/blog`. */
export function stripLocalePrefix(pathname: string): string {
if (pathname === '/pt-br') return '/';
if (pathname.startsWith('/pt-br/')) return pathname.slice('/pt-br'.length);
return pathname;
}
/** `/blog` in a given locale: `/blog` or `/pt-br/blog`. */
export function localizePath(rootPath: string, locale: Locale): string {
const prefix = LOCALE_PREFIX[locale];
if (!prefix) return rootPath;
return rootPath === '/' ? prefix : prefix + rootPath;
}
Notice the startsWith('/pt-br/') with the trailing slash. Without it, a
path like /pt-brazil-trip would count as Portuguese. Small thing, easy
to get wrong, and the kind of edge case worth one unit test.
Why is English unprefixed and not /en? Because the English URLs existed
first, and renaming every one of them would have thrown away whatever
links and search history they had. If you start bilingual from day one,
prefixing both (/en, /pt-br) is perfectly fine and a bit more
symmetric. What you shouldn't do is change the scheme later without
redirects.
In the router, both languages render the same page components. A small function builds the route list once, and it's mounted twice:
function pages(tree: 'en' | 'pt', home: string) {
const id = (name: string) => ({ id: `${tree}-${name}` });
return [
index(home, id('home')),
route('about', 'routes/about.tsx', id('about')),
route('blog', 'routes/blog.tsx', id('blog')),
route('blog/:slug', 'routes/post.tsx', id('post')),
// ...projects, contact, privacy, 404
];
}
export default [
route('/', 'routes/layout.tsx', { id: 'en-layout' }, pages('en', 'routes/root-redirect.tsx')),
route('pt-br', 'routes/layout.tsx', { id: 'pt-layout' }, pages('pt', 'routes/home.tsx')),
] satisfies RouteConfig;
That's React Router's framework-mode config (the site prerenders every
page, see Part 5), but the idea
carries over to any router: one list of pages, mounted under each prefix.
Adding a page adds it in both languages at once, so you can't end up with
an /about that has no /pt-br/about.
Typed dictionaries: a missing translation is a compile error
Each language gets one TypeScript file with every UI string, grouped by page or component. The English one is the reference:
export const en = {
nav: {
home: 'Home',
blog: 'Blog',
// ...
},
blogPost: {
notAvailableNotice:
"This post isn't available in English. Showing the Portuguese version.",
// ...
},
// ...
} as const;
// Widen every leaf from a string literal to `string` so other locales can
// provide their own translated text while keeping the same shape.
type Widen<T> = T extends string ? string : { [K in keyof T]: Widen<T[K]> };
export type Dictionary = Widen<typeof en>;
And the Portuguese file is checked against that shape:
import type { Dictionary } from './en';
export const ptBR = {
nav: {
home: 'Início',
blog: 'Blog',
},
blogPost: {
notAvailableNotice: 'Este post não está disponível em português. ...',
},
// ...
} as const satisfies Dictionary;
The trick is in those two type lines. as const makes TypeScript infer
the English object with literal types: home isn't a string, it's
exactly 'Home'. That's too strict to reuse directly. If you checked the
Portuguese file against typeof en, it would fail on every single string,
because 'Início' is not 'Home'. Widen walks the object and turns
every leaf back into string, while keeping all the keys and the nesting.
Then satisfies Dictionary checks the Portuguese object against that
shape without changing its own type. Both directions of drift are caught.
Leave a key out:
error TS2741: Property 'blog' is missing in type '{ readonly home: "Início"; }'
but required in type '{ readonly home: string; readonly blog: string; }'.
Or add one that English doesn't have (a typo, or a leftover from a removed feature):
error TS2353: Object literal may only specify known properties,
and 'contato' does not exist in type '{ readonly home: string; readonly blog: string; }'.
Both of those come from running tsc on a cut-down copy of these files.
Since the build runs the type checker, a missing translation can't reach
production. You add a string to en.ts, the build goes red, and the error
points at the exact place in pt-BR.ts where it belongs.
What the types can't catch is a translation that's wrong, or one you
pasted in English "for now" and forgot. 'Home' is a perfectly valid
string. A quick search for a few common English words in the Portuguese
file before a release covers most of that.
One provider, and links that keep the language
Pages get their strings from a context. The provider is about twenty lines:
const dictionaries: Record<Locale, Dictionary> = { en, 'pt-BR': ptBR };
export function LocaleProvider({ locale, children }: {
locale: Locale;
children: ReactNode;
}) {
const value = useMemo(
() => ({
locale,
t: dictionaries[locale],
path: (rootPath: string) => localizePath(rootPath, locale),
}),
[locale],
);
return <LocaleContext.Provider value={value}>{children}</LocaleContext.Provider>;
}
The layout derives the locale from the current pathname and wraps
everything in it. It also keeps <html lang> in sync, which screen
readers use to pick a pronunciation and search engines use as one more
language hint. In a page, usage looks like this:
const { t, path } = useLocale();
<Link to={path('/blog')}>{t.nav.blog}</Link>
path() is the part people forget. If a component hardcodes
<Link to="/blog">, a Portuguese reader clicks it and lands in English.
Make the helper the only way to build an internal link and that bug goes
away. Because t is a typed object, t.nav.blgo is a compile error and
your editor autocompletes every key, which is most of what a library's
t('nav.blog') string keys give you, minus the typos.
Both dictionaries are bundled, so there's no loading state and no flash of untranslated text. At 105 strings each that costs a few kilobytes. With ten languages and thousands of strings you'd want to load them on demand, which is one of the library arguments further down.
Remembering the visitor's choice, carefully
The language switcher in the navbar links to the same page in the other
language and saves the choice in a small lang cookie for a year.
The interesting part is where that cookie is read: in exactly one place.
Only the bare root, /, looks at it. A visitor who chose Portuguese last
time and types josealencar.dev gets sent to /pt-br. Every other URL
renders what it says, whatever the cookie holds. If someone shares
/blog/some-post, the person who opens it sees English, because that's
what the link means.
It's tempting to go further: read Accept-Language and redirect everyone
to "their" language. Don't. Google's documentation on locale-adaptive
pages warns that Googlebot usually crawls without an Accept-Language
header, from US addresses, so content that only appears after a
language-based redirect may never get crawled. Redirects based on a guess
also annoy the people the guess gets wrong, like a Brazilian engineer
who wants to read in English. Let the URL decide, offer an obvious
switcher, and remember what the visitor picked.
There's one more detail if you prerender. The HTML for / is built
without any cookie, so it's always the English home page. The redirect
has to happen in the browser, after hydration. This site uses
useSyncExternalStore with a server snapshot of "don't redirect", so
hydration matches the prerendered markup and the redirect runs right after.
Content that exists in only one language
UI strings are one thing. Posts are another, and they're where most of the real decisions are.
Each post is a Markdown file. some-post.md is English;
some-post.pt-BR.md is its optional Portuguese companion, with the same
slug and the same frontmatter fields, translated. Optional is the
important word. Not every post has to exist in both languages: something
about Brazilian employment contracts might only ever make sense in
Portuguese, and a quick English note might never be worth translating.
(So far, every post on this site has both files: 59 and 59. The fallback
exists for the day that stops being true.)
So what does /pt-br/blog/some-post show when there's no Portuguese file?
A 404 would be correct and unhelpful. Here, the page shows the version
that does exist, with a one-line notice in the reader's language saying
so. It works in both directions: an English-only post opened under
/pt-br, or a Portuguese-only post opened without the prefix.
The part that's easy to get wrong is the SEO underneath that friendly
fallback. The page at /pt-br/blog/some-post is showing English content,
so for search engines it's a duplicate of /blog/some-post. Three things
keep it from causing trouble:
- The canonical points at the content's real URL,
/blog/some-post, not at the address the visitor typed. hreflangonly lists languages that actually exist. A post with only an English file has nopt-BRalternate. Pointing an alternate at a fallback page would tell Google "here's the Portuguese version" when there isn't one.- The fallback URL isn't built or listed. The sitemap and the prerender list only include a post in the languages it has a file for. The fallback URL gets the generic SPA shell, served with a real HTTP 404 status, and the fallback is rendered in the browser. People get a readable page; crawlers get a clear "nothing here".
The same rule carries through the rest of the post page: the series' previous/next links and the structured data are built from the content's language, not the visitor's. A Portuguese reader looking at an English fallback should get "next part" links to English posts that exist, not links to Portuguese pages that don't. The surrounding UI (the nav, the notice, the date line) stays in the visitor's language, since that's the language they asked for.
hreflang, canonicals and the sitemap
For pages that exist in both languages, every page declares itself and its
twin. The <Seo> component from Part 8 gets two more props, the
locale-agnostic path and which languages have the content:
{rootPath && (
<>
{availableLocales.map((loc) => (
<link
key={loc}
rel="alternate"
hrefLang={LOCALE_TAG[loc]}
href={SITE_URL + localizePath(rootPath, loc)}
/>
))}
<link rel="alternate" hrefLang="x-default" href={SITE_URL + localizePath(rootPath, 'en')} />
</>
)}
The rules that matter, in the order people usually break them:
- Alternates must be reciprocal. If the English page lists the Portuguese one, the Portuguese page must list the English one back. Google ignores one-sided pairs. Generating both from the same function, as above, makes this automatic.
- Each page lists itself too. The English page has an
enalternate pointing at its own URL. - Each language has its own canonical. The Portuguese page's canonical is the Portuguese URL. A common mistake is pointing every language's canonical at the English page, which tells Google to drop the Portuguese ones from the index.
- Use absolute URLs and valid codes.
pt-BRis a validhreflangvalue (language plus region);bralone is not, it's the code for Breton. x-defaultnames the fallback for visitors whose language you don't have. Here that's English.
The sitemap repeats the same information as xhtml:link entries, one
<url> per page per language, as Part 8 showed.
You don't need both for Google, but both are generated from the same route
list, so they can't contradict each other, and the build's prerender check
fails if a listed page is missing.
The parts that aren't strings
The dictionary is the obvious half. Most of the remaining work is in things that don't look like translation until you miss one:
- Dates.
toLocaleDateStringwith the right tag (enorpt-BR) gives "November 19, 2026" or "19 de novembro de 2026". Never build dates by hand. One trap: a date-only string like2026-11-19is parsed as midnight UTC, so format it withtimeZone: 'UTC'too, or every reader west of Greenwich sees the day before. - Data files. The profile and project list each have a
.pt-BR.tscompanion, typed against the same shape with a type-only import, so the dictionary trick applies to them too. - Tags. Post tags are stored as slugs (
spring-boot) and shared between languages. A small map turns each slug into a display label per language ("Beginners" / "Iniciantes"). There's a side benefit: a browser's automatic page translation is much more likely to mangle a raw lowercase slug, word by word, than a properly cased product name. - Images. Diagrams have text in them. Every post here has a separate
set of SVGs per language (
fallback.svgandfallback.pt-BR.svg), and a separate social preview image, because the preview is the first thing someone sees when the link is shared. - Series titles and metadata. "Build a Developer Portfolio" is
translated in the Portuguese frontmatter, and so are the title and
excerpt, which become the page's
<title>and meta description. - Text length. Portuguese runs noticeably longer than English. Buttons, nav items and those SVG diagrams need room for it. Check every layout in the longer language.
When to use react-i18next or Lingui instead
Hand-rolling stops being the cheap option at fairly clear points:
-
Plurals that depend on the language. Every language has its own plural rules, and a hand-written
n === 1 ? one : otheris wrong for many of them. Even Portuguese differs from English here: by the Unicode CLDR rules thatIntl.PluralRulesfollows, Brazilian Portuguese treats 0 as singular.type PluralForms = Partial<Record<Intl.LDMLPluralRule, string>> & { other: string }; function plural(locale: string, n: number, forms: PluralForms): string { const rule = new Intl.PluralRules(locale).select(n); return (forms[rule] ?? forms.other).replace('{n}', String(n)); } plural('en', 0, { one: '{n} post', other: '{n} posts' }); // "0 posts" plural('pt-BR', 0, { one: '{n} artigo', other: '{n} artigos' }); // "0 artigo"For one or two counted words, a helper like this on top of
Intlis fine. Once you have many messages with counts, genders and nested options, you want ICU message syntax, which is what the libraries give you. -
More than two or three languages, or languages written right to left. You'll want dictionaries loaded on demand and a layout tested in both directions.
-
Translators who aren't developers. Professional translators work in translation management tools with JSON, PO or XLIFF files, not in your TypeScript. Libraries come with the extraction and file formats those tools expect.
-
Copy that changes often, written by people other than the code's owner.
Between the two most common choices: react-i18next is the most widely used and very flexible, with keys stored in JSON files that load at runtime. Lingui takes a compile-time approach: you write the English text in the component, a CLI extracts it into message catalogs, and it uses ICU syntax for plurals. Either is a sound choice when you hit the points above.
If you start hand-rolled, moving later isn't expensive. Typed dictionaries are plain nested objects, so turning them into JSON for a library takes a short script, and the URL scheme, hreflang and sitemap work all stay the same. That's the real reason to start small: the decisions that are hard to change are the URLs, not the string lookup.
The whole series, in nine parts
That's the end of Build a Developer Portfolio. If you came in at the last part, here's the path:
- What to include and what to skip: the few pages a portfolio actually needs.
- Do you still need a personal website?: what a site does that LinkedIn and GitHub don't.
- A step-by-step plan: the build in order, from domain to launch.
- Portfolio examples and the patterns that work.
- Choosing the tech stack: static, SPA or framework, and why this site prerenders.
- Projects as case studies, not code dumps.
- Deploying on Cloudflare Pages: custom domain, HTTPS and the www redirect.
- SEO for a developer portfolio: metadata, sitemaps and structured data.
- Making it bilingual: this post.
A checklist for the bilingual part, before you ship it:
- The language is in the URL, and every page exists under both prefixes.
- The second dictionary is type-checked against the first, and the build runs the type checker.
- Every internal link goes through a
path()-style helper. <html lang>, the canonical and thehreflangalternates are correct on every page, and the alternates are reciprocal.- Nothing redirects based on
Accept-Language. The cookie, if you have one, only affects the bare root. - Content in one language falls back with a notice, and the fallback URL isn't indexed.
- Images and social previews exist in both languages.
What's next
The portfolio series is done, but the blog isn't. If your day job is on the backend, Spring Boot in Production is running now: it starts with configuration, profiles and secrets and goes on to health checks you can trust, then database migrations, testing against real infrastructure, and the rest of what it takes to run a service you're not afraid of. And if you're working on the career side, the Senior Engineer Roadmap collects the 18-part path from mid-level to senior in one place.