Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/wezomcompany/locale-handler
Locale handler for middleware with redirects
https://github.com/wezomcompany/locale-handler
Last synced: 5 days ago
JSON representation
Locale handler for middleware with redirects
- Host: GitHub
- URL: https://github.com/wezomcompany/locale-handler
- Owner: WezomCompany
- License: bsd-3-clause
- Created: 2023-08-03T03:03:16.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2023-10-24T11:55:50.000Z (about 1 year ago)
- Last Synced: 2023-10-24T12:35:42.513Z (about 1 year ago)
- Language: TypeScript
- Size: 188 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# @wezom/locale-handler
> Locale handler for middleware with redirects
Code coverage:
| Statements | Branches | Functions | Lines |
| ---------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------ |
| ![Statements](https://img.shields.io/badge/statements-100%25-brightgreen.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-100%25-brightgreen.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-100%25-brightgreen.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-100%25-brightgreen.svg?style=flat) |GitHub Actions:
[![CI Test and Build](https://github.com/WezomCompany/locale-handler/actions/workflows/ci.yml/badge.svg)](https://github.com/WezomCompany/locale-handler/actions/workflows/ci.yml)---
## Installation
Via [pnpm](https://pnpm.js.org/):
```sh
pnpm add @wezom/locale-handler
```Via [npm](https://www.npmjs.com/):
```sh
npm install @wezom/locale-handler
```Via [yarn](https://yarnpkg.com/):
```sh
yarn add @wezom/locale-handler
```## Usage example with Next.js App Route
According to Next.js documentation
about [Internationalization](https://nextjs.org/docs/app/building-your-application/routing/internationalization),
you can create a own middleware to handle missing locales redirects.```ts
// middleware.ts
import { NextRequest, NextResponse } from 'next/server';
import { LocaleHandler } from '@wezom/locale-handler';export function middleware(request: NextRequest): void | NextResponse {
const localeHandler = new LocaleHandler({
acceptLanguages: request.headers.get('accept-language'),
availableLocales: ['uk', 'en'],
defaultLocale: 'uk',
url: request.nextUrl,
});if (localeHandler.pathnameHasMissingLocale) {
const url = localeHandler.getPreferredLocaleUrl();
return NextResponse.redirect(url);
}
}export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
};
```