Gathering detailed insights and metrics for next-loc
Gathering detailed insights and metrics for next-loc
Gathering detailed insights and metrics for next-loc
Gathering detailed insights and metrics for next-loc
npm install next-loc
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
51 Commits
1 Watching
1 Branches
1 Contributors
Updated on 19 Aug 2024
TypeScript (100%)
Cumulative downloads
Total Downloads
Last day
-50%
2
Compared to previous day
Last week
-11.1%
8
Compared to previous week
Last month
-52.1%
34
Compared to previous month
Last year
0%
2,414
Compared to previous year
4
A modern localisation solution for Next.js, featuring Full TypeScript support, SSR support, easy setup & configuration, included middleware, global dictionaries & dictionary inheritance, compression, and translation deduplication.
Install Next Loc globally:
1npm install -g next-loc
Next Loc requires the following packages to be installed in your project directory:
accept-language
smob
lz-string
(can be changed, see below)Configure Next Loc in your project:
1npx next-loc@latest
Flag | Alternative | Description |
---|---|---|
--default | -d | Use the default configuration. |
--default-dir | -dd | Use the default destination directory (src/locale ). |
Made a mistake during configuration? Just run the command again to overwrite the existing configuration! Be warned, this will overwrite any customisations you have made to destination directory, including the configuration file and middleware.
Next, import the generated middleware into your middleware.ts
or middleware.js
file. The included middleware is designed to be used as the only middleware in your project out-of-the-box, but can be freely modified to adapt to your middleware implementation. Refer to the Next.js docs for more information. Here is an example implementation:
1import { localeMiddleware } from "./path/to/middleware"; 2 3export const middleware = (request: NextRequest, _event: NextFetchEvent) => { 4 return localeMiddleware(request, _event); 5}; 6 7export const config = { 8 matcher: "/((?!api|_next/static|_next/image|favicon.ico).*)", 9};
Create a directory for each locale (with the same name), following the format described by the dictionaryPath
option in the config.ts
file.
Create a JSON file for each namespace (with the same name) within each locale directory, following the format described by the dictionaryPath
option in the config.ts
file.
For example, using the default configuration, the following dictionary files should be created:
src/locale/dictionary/en-GB/common.json
Move all routes into a [locale]
directory, which allows the current locale to be determined using the URL params. See the Next.js docs for more information.
Wrap your app inside the <LocaleContextProvider>
component at your app root, which allows you to access the current locale in client components via the use of the useLocaleContext()
hook. See the locale context documentation for more information. You will also need to add a <DictionaryContextProvider />
component at some point in the component tree, which allows you to access the current dictionary in heir client components via the use of the useDictionaryContext()
hook. See the dictionary context documentation for more information.
translate(key, dictionary, locale)
(not preferred)key
refers to the full dot notation path to the translation. For example, "common.greetings.welcome"
, would be found at the welcome
key, within the greetings
object, within the JSON object in the common.json
file.1// Usage with SSR 2 3import { compileDictionary } from "./path/to/compileDictionary"; 4 5// Get locale from URL params 6 7const dictionary = compileDictionary({ 8 locales: [locale], 9 namespaces: ["common"], 10}); 11const str = translate("common.greetings.welcome", dictionary, locale);
1// Usage with client components 2 3const { locale } = useLocaleContext(); 4const { dictionary } = useDictionaryContext(); 5const str = translate("common.greetings.welcome", dictionary, locale);
See the context documentation for more information.
genT(locale, namespace, dictionary, options)
(preferred)locale
herekey
is appended to the value of namespace
here (.
is added automatically)key
which is always appended to the namespace
here)options
parameter is an optional object containing the following properties:
delayDecompression?: boolean
: If true
, the dictionary will not be decompressed in the generated function. It will instead be decompressed on each translation call.dedup?: boolean
: If true
, the returned function will deduplicate translations. See deduplication for more information.1// Usage with SSR 2 3const t = genT(locale, "common.greetings", dictionary); 4const str = t("welcome");
1// Usage with client components 2 3const t = genT(locale, "common.greetings", dictionary); 4const str = t("welcome");
useAutoGenT(namespace, options, override)
(best)useAutoGenT
is a React Hook provided by Next Loc, which acts as a shorthand for genT(locale, namespace, dictionary)
. It can be used in client components to prevent having to call useLocaleContext()
and useDictionaryContext()
to get the locale and dictionary. Instead, the locale and dictionary are retrieved from context within the hook itself. The options
parameter is identical to that of genT
. The override
parameter is an optional object containing the following properties:
locale?: NextLocTypes.Locale
: Override the locale used in the hookdictionary?: NextLocTypes.ThisDictionaryType
: Override the dictionary used in the hookNext Loc includes a locale context provider to make it easier to access the current locale in client components. The recommended usage is to set the context at the app root.
1export default function RootLayout({ 2 children, 3 params: { locale }, 4}: Readonly<{ children: React.ReactNode }> & NextLocTypes.LocaleParam) { 5 return ( 6 <html lang={locale}> 7 <body> 8 <LocaleContextProvider {...{ locale }}> 9 {children} 10 </LocaleContextProvider> 11 <LocaleLogProvider /> 12 </body> 13 </html> 14 ); 15}
Use useLocaleContext()
to access the locale in client components.
1const { locale } = useLocaleContext();
Next Loc includes a dictionary context provider to make it easier to access the current dictionary in client components. The recommended usage is to import the locales & namespaces you need (using compileDictionary
) and use the context provider to expose the dictionary to any child components which require a certain part of the dictionary. This prevents having to pass the entire dictionary to context, instead only having what is needed available. Here is an exmaple:
1import { compileDictionary } from "./path/to/compileDictionary"; 2 3export const SSRComponent = ({ 4 children, 5 params: { locale }, 6}: Readonly<{ children: React.ReactNode }> & NextLocTypes.LocaleParam) => { 7 const dictionary = compileDictionary({ 8 locales: [locale], 9 namespaces: ["common"], 10 }); 11 12 return ( 13 <DictionaryContextProvider {...{ dictionary }}> 14 {children} 15 </DictionaryContextProvider> 16 ); 17};
Use useDictionaryContext()
to access the, now much smaller, dictionary in client components.
1const { dictionary } = useDictionaryContext();
For small sites, or sites where performance is not a concern, you may opt to include the entire dictionary in the app root, meaning that all localisations will be available to all components. For larger sites, you may consider creating additional dictionary contexts, for example, a global dictionary context, which might contain some commonly used translations. You will need to pass any non-default dictionaries to the override parameter of the useAutoGenT
hook when using it.
1export default function RootLayout({
2 children,
3 params: { locale },
4}: Readonly<{ children: React.ReactNode }> & NextLocTypes.LocaleParam) {
5 const dictionary = compileDictionary({
6 // you may also pass `localeConfig.supported.locales` here if you want to include all supported locales
7 locales: [locale],
8 namespaces: [
9 ...localeConfig.supported.namespaces,
10 ...localeConfig.supported.globalNamespaces,
11 ],
12 });
13
14 return (
15 <html lang={locale}>
16 <body>
17 <LocaleContextProvider {...{ locale }}>
18 <DictionaryContextProvider {...{ dictionary }}>
19 {children}
20 </DictionaryContextProvider>
21 </LocaleContextProvider>
22 <LocaleLogProvider />
23 </body>
24 </html>
25 );
26}
Next Loc also includes a context provider for the translate
function. This allows you to create a translate function using genT
, then pass it to the <TranslationContextProvider />
component, then use useTranslationContext()
to access the translate function in client components.
1export const Component = () => { 2 const t = genT(locale, "common.greetings", dictionary); 3 // OR `const t = useAutoGenT("common.greetings");` if client-side 4 5 return ( 6 <TranslationContextProvider translator={t}> 7 <ChildComponent /> 8 </TranslationContextProvider> 9 ); 10};
1// Child (client) component 2 3export const ChildComponent = () => { 4 const { translator: t } = useTranslationContext(); 5 6 return <p>{t("welcome")}</p>; 7};
Next Loc makes some checks to ensure that localisation will function as expected (these can be inspected in internal/checks.ts
). To enable these checks, add the <LocaleLogProvider />
component at the app root.
These checks cover:
localePattern
specified in the config.ts
fileNext Loc generates a configuration file, config.ts
within the destination directory. This file can be freely modified to suit your needs. This is the default configuration that is generated with the default options during setup:
1{ 2 supportedLocales: ["en-GB"], 3 supportedNamespaces: ["common"], 4 globalNamespaces: [], 5 defaultLocale: "en-GB", 6 defaultNamespace: "common", 7 cookieName: "hl", 8 localePattern: /[a-z]{2}-[A-Z]{2}/, 9 dictionaryPath: "src/locale/dictionary/{locale}/{namespace}.json", 10 inherits: {}, 11 ignoreMiddleware: [ 12 "/static", 13 "/api", 14 "/_next", 15 "favicon.ico", 16 "robots.txt", 17 "sitemap.xml", 18 ], 19 suppress: { 20 missingDictionary: false, 21 localeSatisfiesPattern: false, 22 defaultLocaleIsSupported: false, 23 }, 24 optOutCompression: false, 25}
supportedLocales
A string array, containing the locales supported by your application.
supportedNamespaces
A string array, containing the namespaces supported by your application. Each namespace corresponds to an indiviual JSON file located inside each dictionary directory.
globalNamespaces
A string array, containing the namespaces found in the GLOBAL
directory, available for all locales.
defaultLocale
The default locale, used when no cookie is set, and the request URL contains no supported locale.
defaultNamespace
The namespace used for finding localisations when no namespace is provided to the translator function.
cookieName
The name of the cookie used to store the selected locale in the user's browser.
localePattern
The pattern for supported locales. This is used when the request URL does not contain a supported locale, to determine if the user is trying to access a valid, but not supported locale. For example, using the default configuration, the URL /de-DE/page
would be redirected to en-GB/page
, because de-DE
satisfies the localePattern
. Whereas the URL something/page
would be redirected to en-GB/something/page
, because something
does not satisfy the localePattern
.
dictionaryPath
The path to the JSON dictionary files. This should include {locale}
and {namespace}
to point to the correct files for each locale and namespace during dictionary compilation. See Using Non-JSON Dictionaries below for more information.
inherits
Declare dictionary inheritance, in the format { {locale}: {other locales}[], ... }
. See inheritance below for more information.
ignoreMiddleware
An array of paths for which the middleware will return an unmodified response. This is useful for ignoring static files which should not differ based on locale, such as /favicon.ico
. Middleware execution can be prevented via the config
object within middleware.ts
, as referenced by the Next.js docs. Paths in ignoreMiddleware
will NOT prevent middleware from being executed.
suppress
Allows you to suppress certain errors.
missingDictionary
: If true
, no errors will be shown when a dictionary is missing. If an array containing locales is provided, only errors for those locales will be suppressed.localeSatisfiesPattern
: If true
, no errors will be shown when a locale does not satisfy the localePattern
specified in the config.ts
file.defaultLocaleIsSupported
: If true
, no error will be shown when the default locale is not included as a supported locale.optOutCompression
If true
, Next Loc will not compress the dictionary object. See the section on compression below for more information.
Next Loc provides a property in the config object, inherits
, which allows locales to inherit translations from other locales. This is useful for implementing locales for different cultures within the same language. For example, if your site has the locale en-GB
, but you also want to support the locale en-US
, instead of copying every file from the en-GB
directory, you can simply add the following to the config.ts
file:
1inherits: { 2 "en-US": ["en-GB"] 3}
This means that every localisation from en-GB
is inherited by en-US
. From here, you can add unique translations to en-US
as normal, and they will overwrite the translations inherited from en-GB
. To prevent errors due to missing dictionary files for en-US
, make sure to set suppress.missingDictionary
to true
, or include en-US
in its array.
Next Loc also provides support for global dictionaries. A global dictionary is, in essence, "inherited" by ALL locales. To use global dictionaries, create a GLOBAL
directory in the same directory as the normal locales. Within this GLOBAL
directory, create a JSON file for each member of globalNamespaces
in config.ts
. Translations located in global dictionaries are accessed in the same way as regular localisations. For example, if there is a file GLOBAL/metadata.json
, its translations can be accessed as follows.
1//... 2 3<p>{translate("metadata.site.title", locale, dictionary)}</p> 4 5//...
Dictionaries are compiled in the following order:
inherits
propertyFor example, if en-US
inherits from ["en-GB", "en-CA"]
, and the application makes use of global dictionaries, the global dictionaries will be compiled first, then merged with the inherited dictionaries, first en-GB
, then en-CA
, any conflicts being overwritten by the inherited dictionaries in the order of their declaration (en-CA
overwrites conflicts with en-GB
), then the regular dictionaries for en-US
will be compiled last, any conflicts being overwritten by the regular dictionaries.
Next Loc includes support for compressing the dictionary object. The default and recommended compression method is achieved via the use of lz-string. To change the compression (and decompression) functions, modify the compressFunction
and decompressFunction
functions exported from internal/compression.ts
. For small sites with a small amount of text, or a small number of locales, you should consider opting out of compression to improve performance.
Next Loc includes support for deduplication of translations. This can be achieved by setting the dedup
option in a genT
or useAutoGenT
call to true
. This will ensure that for any usage of the returned translator function, only one translation will be computed from the dictionary, and all future calls with the same key will return a copy of the first translation. Here is an example:
1export const Component = ({ someData }: { someData: Data[] }) => { 2 const t = useAutoGenT("common.greetings", { dedup: true }); 3 4 return ( 5 <div> 6 {someData.map((dataPoint) => { 7 return <div key={dataPoint.id}>{t("welcome")}</div>; 8 })} 9 </div> 10 ); 11};
In the above example, the translation for common.greetings.welcome
will only be computed once, each subsequent call to t("welcome")
will return a copy of the first translation.
Next Loc currently does not have out-of-the-box support for non-JSON dictionaries. You may be able to achieve this functionality by doing the following:
dictionaryPath
option in the configuration file, to use the necessary file extension.compileDictionary
function in internal/compileDictionary.ts
,
JSON.parse(fileContents)
to a custom functionNo vulnerabilities found.
No security vulnerabilities found.
@lerna/create
Create a new lerna-managed package
func-loc
Retrieve the function location from it reference in NodeJS.
gatsby-plugin-sitemap
Gatsby plugin that automatically creates a sitemap for your site
@fmvilas/pseudo-yaml-ast
Fork of pseudo-yaml-ast. Parse a YAML string into an object with location properties