Enhance your Astro development experience with rigorous type safety for every route in your application. This integration automatically generates TypeScript definitions from your project's route structure.
Works with Astro version 4 and 5, with a minimum of 4.14.0
.
- Add integration:
npx astro add astro-typesafe-routes
- Start the Astro development server if it's not already running to run type generation:
npm run dev
- Install package:
npm install -D astro-typesafe-routes
- Add integration to
astro.config.mjs
:
import { defineConfig } from 'astro/config';
import astroTypesafeRoutes from "astro-typesafe-routes"
export default defineConfig({
integrations: [
astroTypesafeRoutes()
]
});
- Start the Astro development server if it's not already running to run code generation:
npm run dev
Import the Link
component and use it as a drop-in replacement for links.
---
import Link from "astro-typesafe-routes/link";
---
<Link to="/blog/[id]" params={{ id: "4" }}>Blog post</Link>
If you can't or don't want to use the Link
component, you can use the $path
function to ensure safe URLs.
---
import { $path } from "astro-typesafe-routes";
---
<a href={$path("/blog/[id]", { params: { id: "4" } })}>
Blog Post
</a>
Both the $path
function and Link
component also accepts the optional fields search
, hash
and trailingSlash
.
---
import Link from "astro-typesafe-routes/link";
---
<Link
to="/blog/[id]"
params={{ id: "4" }}
hash="header"
search={{ filter: "recent" }}
>
Slug here
</Link>
Import Route
and RouteOptions
types to add type safety to your custom link components:
---
import { HTMLAttributes } from "astro/types";
import { $path, type RouteOptions } from "../index";
export type Props = Omit<HTMLAttributes<"a">, "href"> & RouteOptions;
const { to, params, search, hash, trailingSlash, ...anchorProps } = Astro.props;
const href = $path({ to, params, search, hash, trailingSlash });
---
<a href={href} {...anchorProps}>
<slot />
</a>
Inspiration taken from yesmeck/remix-routes.