https://github.com/scriptedalchemy/next-known-route
Check if a url is a known route to a next.js application ahead of time
https://github.com/scriptedalchemy/next-known-route
Last synced: 10 months ago
JSON representation
Check if a url is a known route to a next.js application ahead of time
- Host: GitHub
- URL: https://github.com/scriptedalchemy/next-known-route
- Owner: ScriptedAlchemy
- License: mit
- Created: 2022-05-19T17:05:31.000Z (almost 4 years ago)
- Default Branch: main
- Last Pushed: 2023-12-15T02:57:37.000Z (about 2 years ago)
- Last Synced: 2025-04-14T12:54:14.988Z (11 months ago)
- Language: JavaScript
- Size: 25.4 KB
- Stars: 13
- Watchers: 2
- Forks: 2
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# next-known-route
Check if a url is a known route to a next.js application ahead of time.
https://www.npmjs.com/package/next-known-route
# Use Case
Why do you need this? Next does not offer a way to know if a url matches a known route with the application.
The only way to do it out the box is to try and preload the route, which is wasteful & only works on the client.
- Understanding internal vs external links during render or elsewhere in your application (like utils)
- SEO - no follow links to external sources.
- Any feature that requires a page manifest lookup.
- Dynamic navigation and route expressions matching.
No third party dependencies, this is all made possible by using internal parts of next router.
# Usage:
In `_app` add the following and return it from `getInitialProps`
```js
import { getRouteManifest, isKnownRoute } from 'next-known-route'
const MyApp = ()=>{
const internalRoute = isKnownRoute('/') // or whatever path you want to check aganst. Returns true|false
return ()
}
MyApp.getInitialProps = async (appContext) => {
const appProps = await App.getInitialProps(appContext);
const props = {
...appProps,
knownRoutes: getRouteManifest() // returns ['/_app','/','/[...slug]']
};
return props
}
```
## Features
- Works on server and client
- No external libraries needed, only 50 LOC
- `getRouteManifest` accepts an array of additional path expressions to match against.
Contributions are welcome.