{"id":18715413,"url":"https://github.com/rawnly/next-wayfinder","last_synced_at":"2025-04-12T13:08:39.460Z","repository":{"id":65856793,"uuid":"575690305","full_name":"rawnly/next-wayfinder","owner":"rawnly","description":"Apply multiple nextjs middlewares with ease","archived":false,"fork":false,"pushed_at":"2024-03-31T12:48:39.000Z","size":602,"stargazers_count":22,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-04-12T13:08:34.105Z","etag":null,"topics":["middleware","next"],"latest_commit_sha":null,"homepage":"https://next-wayfinder.dev","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rawnly.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2022-12-08T04:33:33.000Z","updated_at":"2025-04-05T12:00:15.000Z","dependencies_parsed_at":"2023-02-14T07:25:14.840Z","dependency_job_id":"295a6278-eda7-4c7d-8d0f-00e5034e5fd4","html_url":"https://github.com/rawnly/next-wayfinder","commit_stats":{"total_commits":30,"total_committers":3,"mean_commits":10.0,"dds":0.4,"last_synced_commit":"870e4da8a751ba41e9da2a936d690bcadc9379eb"},"previous_names":[],"tags_count":7,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rawnly%2Fnext-wayfinder","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rawnly%2Fnext-wayfinder/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rawnly%2Fnext-wayfinder/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rawnly%2Fnext-wayfinder/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rawnly","download_url":"https://codeload.github.com/rawnly/next-wayfinder/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248571892,"owners_count":21126522,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["middleware","next"],"created_at":"2024-11-07T13:08:38.699Z","updated_at":"2025-04-12T13:08:39.422Z","avatar_url":"https://github.com/rawnly.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cbr/\u003e\n  \u003ca aria-label=\"NPM version\" href=\"https://www.npmjs.com/package/next-wayfinder\"\u003e\n    \u003cimg alt=\"\" src=\"https://badgen.net/npm/v/next-wayfinder\"\u003e\n  \u003c/a\u003e\n  \u003ca aria-label=\"Package size\" href=\"https://bundlephobia.com/result?p=next-wayfinder\"\u003e\n    \u003cimg alt=\"\" src=\"https://badgen.net/bundlephobia/minzip/next-wayfinder\"\u003e\n  \u003c/a\u003e\n  \u003ca aria-label=\"License\" href=\"https://github.com/rawnly/next-wayfinder/blob/main/LICENSE\"\u003e\n    \u003cimg alt=\"\" src=\"https://badgen.net/npm/license/next-wayfinder\"\u003e\n  \u003c/a\u003e\n\u003c/p\u003e\n\n# Introduction\n\n`next-wayfinder` is a lightweight (_~3kb minzipped_) and flexible package that simplifies the organization of middleware in Next.js applications.\nWith `next-wayfinder`, you can easily apply different middlewares based on the route or hostname, without having to use cumbersome and error-prone path checks.\n\nTraditionally, managing middleware in Next.js can be challenging, especially when dealing with complex routing scenarios.\nFor example, you may want to apply an authentication middleware only for certain paths or a subdomain-specific middleware for certain hostnames.\nWith `next-wayfinder`, you can easily manage and maintain your middleware and keep your code clean and organized.\n`next-wayfinder` exports an `handlePaths` function that can be used as middleware entry point.\nIt accepts an array of `Middleware` objects that match the route or hostname, and applies the first matching middleware.\nThis allows you to easily handle complex routing scenarios and reduce the amount of code needed to manage your middleware.\n\n## Installation\n\n```sh\n  npm install next-wayfinder\n```\n\n## Why\n\n`next-wayfinder` was created based on [this discussion][discussion-link] that highlighted the difficulty of handling complex routing inside the Next.js middleware.\nTraditionally, if you want to apply different middlewares for different routes in Next.js, you have to use cumbersome and error-prone path checks.\nFor instance, you might want to have an authentication middleware only for paths matching `/dashboard/:path*` and a subdomain-specific middleware on another set of routes.\nAs of now, this can be achieved through ugly path checking inside a middleware that matches almost all the routes.\n\nWith `next-wayfinder`, you can declare sub-middlewares via `path-regexp` and custom rules in order to achieve a nice, clear middleware file where you can come back after months and instantly understand what's happening.\nThis makes it easy to handle complex routing scenarios and keep your code organized.\nIn summary, `next-wayfinder` simplifies middleware management in Next.js applications and reduces the amount of code needed to manage your middleware, making it easier to write and maintain clean, organized code.\n\n## Quick Start\n\n`next-wayfinder` exports an `handlePaths` function that can be used as middleware entry point.\nIt accepts an array of [`Middleware`](./src/types.ts) objects that match route or hostname, and applies the first matching middleware.\n\n```ts\n// middleware.ts\n\nimport { handlePaths } from \"next-wayfinder\";\nimport { NextResponse } from \"next/server\";\n\n// the first matching middleware will be applied\nexport default handlePaths(\n    [\n        {\n            path: \"/dashboard/:lang/:path*\",\n            // We can filter this to apply only if some params matches exactly our needs\n            guard: params =\u003e params.lang === \"en\",\n            handler: async req =\u003e {\n                // url params are injected by `handlePaths`\n                // in addition to req.query\n                // this is done because you might want to handle paths\n                // that are not available under your `app` or `pages` directory.\n                console.log(req.params);\n\n                // do some checks\n                if (!isAuthenticated(req)) {\n                    return NextResponse.redirect(\"/\");\n                }\n\n                // continue the request\n                return NextResponse.next();\n            },\n        },\n        {\n            hostname: /^app\\./,\n            // rewrites all routes on hostname app.* to the `pages/app/\u003cpath\u003e`\n            handler: req =\u003e\n                NextResponse.rewrite(\n                    new URL(\"/app${req.nextUrl.pathname}\", req.url)\n                ),\n        },\n        {\n            // easy syntax for redirects\n            path: \"/blog/:slug/edit\",\n            // params will be replaced automatically\n            redirectTo: \"/dashboard/posts/:slug\",\n        },\n    ],\n    {\n        // inject custom data, like session etc\n        // it will be available inside `req.ctx`\n        context: async req =\u003e ({ isLoggedIn: !!req.session }),\n        debug: process.env.NODE_ENV !== \"production\",\n    }\n);\n```\n\n### What if I want to check paths on subdomain?\n\nIn some cases, you might want to check paths on a subdomain (i.e., using the same project for handling both the public website and the dashboard).\nThis can be easily achieved by passing an array of middleware as a handler. The `handlePaths` function iterates recursively over all the items provided (including nested ones), so a very high level of complexity can be \"handled\". However, to improve performance, I would recommend keeping it as simple as possible.\n\n```ts\n// middleware.ts\n\nexport default handlePaths([\n    {\n        hostname: /^app\\./,\n        handler: [\n            {\n                path: \"/\",\n                handler: req =\u003e\n                    NextResponse.redirect(new URL(\"/dashboard\", req.url)),\n            },\n            {\n                path: \"/:path*\",\n                handler: () =\u003e NextResponse.next(),\n            },\n        ],\n    },\n]);\n```\n\n### Example - Supabase Authentication\n\n```ts\n// middleware.ts\nimport { NextResponse, NextRequest } from \"next/server\";\nimport { handlePaths, NextREquestWithParams } from \"next-wayfinder\";\nimport { createMiddlewareSupabaseClient } from \"@supabase/auth-helpers-nextjs\";\n\nconst getSession = async (req: NextRequestWithParams) =\u003e {\n    const res = NextResponse.next();\n    const supabase = createMiddlewareSupabaseClient({ req, res });\n\n    const {\n        data: { session },\n        error,\n    } = await supabase.auth.getSession();\n\n    if (error) {\n        console.error(`Auth Error: `, error);\n        return null;\n    }\n\n    return session;\n};\n\nexport default handlePaths(\n    [\n        {\n            // auth guard\n            path: \"/dashboard/:path*\",\n            pre: req =\u003e\n                req.ctx?.session ? true : { redirectTo: \"/auth/sign-in\" },\n            handler: (req, res) =\u003e {\n                console.log(\"User authenticated: \", req.ctx?.session);\n\n                // do your stuff here\n                return res;\n            },\n        },\n    ],\n    {\n        // this injects `session` property into the request object\n        context: async req =\u003e {\n            const session = await getSession(req);\n\n            return { session };\n        },\n    }\n);\n```\n\n### Options\n\nYou can pass several options to configure your middleware\n\n```ts\ninterface WayfinderOptions\u003cT\u003e {\n  debug?: boolean;\n\n  /**\n   *\n   * A function that returns the data to be injected into the request\n   */\n  context?: \u003cT\u003e((request: NextRequest) =\u003e T) | T;\n\n  /**\n   * Global middleware to be executed before all other middlewares\n   * Useful if you want to set a cookie or apply some logic before each request\n   * It receives the `options.response` (or `NextResponse.next()` if not provided) and `NextRequest` as params\n   */\n  beforeAll?: (request: NextRequest, response: NextResponse) =\u003e Promise\u003cNextResponse\u003e | NextResponse;\n\n  /**\n   *\n   * A function to extract `hostname` and `pathname` from `NextRequest`\n   */\n  parser?: RequestParser;\n\n  /**\n   * The response to be used.\n   * Useful when you want to chain other middlewares or return a custom response\n   * Default to `NextResponse.next()`\n   */\n  response?: NextResponse | ((request: NextRequest) =\u003e NextResponse);\n}\n```\n\n## Authors\n\nThis library is created by [Federico Vitale](https://untitled.dev) - ([@rawnly](https://github.com/rawnly))\n\n## License\n\nThe MIT License.\n\n[discussion-link]: https://github.com/vercel/next.js/discussions/43816#discussioncomment-4348363\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frawnly%2Fnext-wayfinder","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frawnly%2Fnext-wayfinder","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frawnly%2Fnext-wayfinder/lists"}