next-language-detector
TypeScript icon, indicating that this package has built-in type declarations

1.1.0 • Public • Published

Introduction

Actions npm version

This package helps to handle language detection in Next.js when using static servers only.

Error: i18n support is not compatible with next export. See here for more info on deploying: https://nextjs.org/docs/deployment

If this error message sounds familiar to you, this module may help.

Getting started

Source can be loaded via npm.

# npm package
$ npm install next-language-detector

Usage:

A complete example can be found here.

And for a step by step guide please have a look at this tutorial.

// lngDetector.js
import languageDetector from 'next-language-detector'
import i18nextConfig from '../next-i18next.config'

export default languageDetector({
  supportedLngs: i18nextConfig.i18n.locales,
  fallbackLng: i18nextConfig.i18n.defaultLocale
})
// redirect.js
import { useEffect } from 'react'
import { useRouter } from 'next/router'
import lngDetector from './lngDetector'

export const useRedirect = (to) => {
  const router = useRouter()
  to = to || router.asPath

  // language detection
  useEffect(() => {
    const detectedLng = lngDetector.detect()
    if (to.startsWith('/' + detectedLng) && router.route === '/404') {
      router.replace('/' + detectedLng + router.route)
      return
    }

    lngDetector.cache(detectedLng)
    router.replace('/' + detectedLng + to)
  })

  return <></>
}
// index.js
import { useRedirect } from '../lib/redirect';

export default function Redirect() {
  useRedirect();
  return <></>;
};

Package Sidebar

Install

npm i next-language-detector

Weekly Downloads

19,955

Version

1.1.0

License

MIT

Unpacked Size

55.7 kB

Total Files

18

Last publish

Collaborators

  • adrai
  • jamuhl