Thanks to visit codestin.com
Credit goes to github.com

Skip to content

aligon/simple-router

Repository files navigation

Simple Router Expirement

Inspired by @tanstack/react-router's inclusion of search params in route definition, but also not being a huge fan of nested routes defining a parent (rather than the parent defining the nested routes). The goal here was to explore and prove out some ideas on how it might could be done differently.

Introduction

A type-safe, nested, non-opinionated TS routing framework.

typesafe

From route definitions, links can be generated with type-safety for the path and query params.

Path Params

Route("profile", "/profile/:id").withHandler((match) => {
	return profileRouteOutput;
});

Links.getLink(Links.root.profile, {
	// TS knows that the path params need an `id` property
	pathParams: { id: "user-1" },
});

Query Params

type PostsParams = {
	sort: string | null,
	filter: string | null,
};

Route("posts", "/posts", {
	encodeSearch: (params: PostsParams) => {
		return createURLSearchParamsForPostParms(params);
	},
	decodeSearch: (params) => ({
		sort: params.get("sort"),
		filter: params.get("filter"),
	}),
}).withHandler((match) => {
	return postRouteOutput;
});

Links.getLink(Links.root.post, {
	pathParams: {},
	// TS knows this needs to be of type PostParams
	searchParams: {
		sort: "created",
		filter: null,
	},
});

nested

Nest routes as children, to create whatever route tree you need.

const Root = Route("root", "/").withRoute(
	Route("account", "/account").withRoute("settings", "/settings")
);

const AccountLink = Links.getLink(Links.root.account);
const SettingsLink = Links.getLink(Links.root.account.settings);

non-opinionated

  • Route output can be whatever you want
  • Organize route definitions however you want

Improvements

  • Better type-safety around the results
  • Allow for other properties to be defined within the route tree (ie Navigation Item Info)

Question and Answers

- Why not just use the file based routing?

You probably should... I'm not even sure I wouldn't... Just haven't had a reason to yet. My initial reaction is Code > Config, and the file based routing FEELS like it belongs more on the Config side of that expression.

- Should I use this in production?

If anyone is actually using your app, please don't... This was just written by one dev trying to prove out enough of half an idea to satisfy my curiosity.

- I REEEAAAALLLLYYY want to use it though

If you feel that strongly, I won't stop you. I might even be interested in collaborating on expanding it out into a production ready routing framework.

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors