Feat(i18n): introduce internalization
I propose to have system to i18n the project.
Using:
- nextjs middleware
- react-intl for i18n key
Problem to solve:
- How to translate product name
We are not planning to add i18n here, but would love to see forked versions that include i18n which we could link back! 🙏
As I've looked into this, the decision not to add it is mostly due to Shopify's own i18n limitations. There's apps / plugins that will add some i18n functionality, but even for built-in features like pages doesn't seem to have a way to support multiple languages.
If you have other experience, as @leerob said, we'd love to see a fork or an example.
One option for anyone who finds this issue is to pass country and/or language variables so that the GraphQL queries can be decorated with @inContext.
For example:
# lib/shopify/types.ts
export type ShopifyCollectionProductsOperation = {
data: {
collection: {
products: Connection<ShopifyProduct>;
};
};
variables: {
handle: string;
reverse?: boolean;
sortKey?: string;
language?: string;
country?: string;
};
};
# lib/shopify/index.ts
export async function getCollectionProducts({
collection,
reverse,
sortKey,
language,
country
}: {
collection: string;
reverse?: boolean;
sortKey?: string;
language?: string;
country?: string;
}): Promise<Product[]> {
const res = await shopifyFetch<ShopifyCollectionProductsOperation>({
query: getCollectionProductsQuery,
tags: [TAGS.collections, TAGS.products],
variables: {
handle: collection,
reverse,
sortKey: sortKey === 'CREATED_AT' ? 'CREATED' : sortKey,
language,
country
}
});
if (!res.body.data.collection) {
console.log(`No collection found for \`${collection}\``);
return [];
}
return reshapeProducts(removeEdgesAndNodes(res.body.data.collection.products));
}
# lib/shopify/queries/collection.ts
export const getCollectionProductsQuery = /* GraphQL */ `
query getCollectionProducts(
$handle: String!
$sortKey: ProductCollectionSortKeys
$reverse: Boolean
$country: CountryCode
$language: LanguageCode
) @inContext(country: $country, language: $language) {
collection(handle: $handle) {
products(sortKey: $sortKey, reverse: $reverse, first: 100) {
edges {
node {
...product
}
}
}
}
}
${productFragment}
`;
Then, you can pass in a language identifier like EN or JA based on the current i18n locale, and/or a country identifier like US or JP if you're letting users choose their country. You should be able to repeat that pattern for other queries, as needed.
In addition to what @zenzen-sol I tried to solve this recently using a middleware that detects user's geolocation through Vercel functions. So in this case sets the country in the cookies and you can retrieve them to make usage of the @inContext directive in a correct way.
Taking in count this is a custom template none of the Shopify location apps gave me result so that's why I decided to implement it in this way. Nevertheless there's an existing bug in this solution that need's a page reload to force user's country.
Hope this approach help you! :)
Middleware.ts
import { geolocation } from '@vercel/functions';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
export function middleware(request: NextRequest) {
const { nextUrl } = request;
// Get geolocation data
let country: string | undefined;
try {
const geoData = geolocation(request);
country = geoData?.country;
console.log('Geolocation data:', geoData);
} catch (error) {
console.error('Error getting geolocation:', error);
}
// Extract the language from the URL (Next.js has locale support)
const locale = nextUrl.locale;
// Update the URL search parameters with the language
nextUrl.searchParams.set('lang', locale);
// Remove the language prefix from the URL path to avoid redundancy
const pathWithoutLocale = nextUrl.pathname.replace(`/${locale}`, '');
nextUrl.pathname = pathWithoutLocale;
// Create a new response
const response = NextResponse.rewrite(nextUrl);
// Set cookie with the country information
if (country) {
response.cookies.set('user-country', country, {
path: '/',
maxAge: 3600, // 1 hour
sameSite: 'strict'
});
// Set header with the country information (optional, but can be useful)
response.headers.set('x-user-country', country);
} else {
console.warn('Country information not available');
}
return response;
}
// Optionally, you can specify which routes this middleware should run on
export const config = {
matcher: '/((?!api|_next/static|_next/image|favicon.ico).*)'
};
Layout.tsx
export default async function RootLayout({ children }: { children: ReactNode }) {
const cartId = cookies().get('cartId')?.value;
const cart = getCart(cartId);
const country = cookies().get('user-country')?.value || 'US';
const lang = await getLangByCountry(country);
return (
<html className={`${inter.className} ${fontBluemont.variable}`}>
<body className="bg-bg-1 text-main-1">
<ClientWrapper>
<LangProvider country={country}>
<CartProvider cartPromise={cart}>
<Navbar activeLang={lang} />
<main className="relative">{children}</main>
<Toaster />
</CartProvider>
</LangProvider>
</ClientWrapper>
</body>
</html>
);
}