Autocorrect for your website URLs
npm install fuzzy-redirectbash
npm install fuzzy-redirect
or
yarn add fuzzy-redirect
or
pnpm add fuzzy-redirect
`
Usage
$3
Use the useFuzzyRedirect hook in your 404 component or a global layout.
`tsx
import React from 'react';
import { useFuzzyRedirect } from 'fuzzy-redirect';
const validRoutes = ['/about', '/contact', '/products', '/blog'];
const NotFound = () => {
// Automatically redirects if a close match is found
const redirectedTo = useFuzzyRedirect({ routes: validRoutes });
if (redirectedTo) {
return Redirecting to {redirectedTo}...
;
}
return 404 - Page Not Found
;
};
export default NotFound;
`
$3
`tsx
// pages/404.tsx
import { useFuzzyRedirect } from 'fuzzy-redirect/next';
const validRoutes = ['/about', '/contact', '/products'];
export default function Custom404() {
useFuzzyRedirect({ routes: validRoutes });
return 404 - Page Not Found
;
}
`
$3
`tsx
// app/not-found.tsx
'use client';
import { useAppFuzzyRedirect } from 'fuzzy-redirect/next-app';
const validRoutes = ['/about', '/contact', '/products'];
export default function NotFound() {
useAppFuzzyRedirect({ routes: validRoutes });
return 404 - Page Not Found
;
}
`
$3
You can also use the core logic directly without any framework dependencies.
`ts
import { findClosestRoute } from 'fuzzy-redirect/core';
const match = findClosestRoute('/abuot', ['/about', '/contact']);
console.log(match); // '/about'
`
Configuration
You can pass an options object to customize the matching behavior.
`ts
useFuzzyRedirect({
routes: validRoutes,
options: {
threshold: 3, // Max edit distance (default: 3)
relativeThreshold: 0.4 // Max distance relative to string length (default: 0.4)
}
});
`
Auto-Generate Routes
Instead of manually maintaining the route list, you can auto-generate it.
$3
Run the generator script to scan your pages/ or app/ directory and create a fuzzy-routes.ts file.
`bash
npx fuzzy-redirect-gen
`
Then import it in your 404 page:
`tsx
import { fuzzyRoutes } from '../fuzzy-routes'; // Adjust path
import { useFuzzyRedirect } from 'fuzzy-redirect/next';
export default function Custom404() {
useFuzzyRedirect({ routes: fuzzyRoutes });
return 404 - Page Not Found
;
}
`
$3
If you are using createBrowserRouter (Data APIs), you can extract routes from your configuration.
`tsx
import { createBrowserRouter } from 'react-router-dom';
import { extractRoutes, FuzzyRedirect } from 'fuzzy-redirect';
const routes = [
{ path: '/', element: },
{ path: '/about', element: },
// ...
];
const router = createBrowserRouter(routes);
const validRoutes = extractRoutes(routes);
// In your NotFound component
``