Skip to content

๐Ÿ›Ÿ An Astro integration for typesafe URL generation and routing, ensuring you never have broken links.

License

Notifications You must be signed in to change notification settings

feelixe/astro-typesafe-routes

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

Astro Typesafe Routes

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.

npm version

Usage demo

Requirements

Works with Astro version 4 and 5, with a minimum of 4.14.0.

Installation

  1. Add integration:
npx astro add astro-typesafe-routes
  1. Start the Astro development server if it's not already running to run type generation:
npm run dev

Manual Installation

  1. Install package:
npm install -D astro-typesafe-routes
  1. Add integration to astro.config.mjs:
import { defineConfig } from 'astro/config';
import astroTypesafeRoutes from "astro-typesafe-routes"

export default defineConfig({
  integrations: [
    astroTypesafeRoutes()
  ]
});
  1. Start the Astro development server if it's not already running to run code generation:
npm run dev

Usage

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>

Typed Custom Component Props

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>

Credit

Inspiration taken from yesmeck/remix-routes.

About

๐Ÿ›Ÿ An Astro integration for typesafe URL generation and routing, ensuring you never have broken links.

Resources

License

Stars

Watchers

Forks

Packages

No packages published