End-to-end typesafe APIs in Astro wesbites made easy

Overview

logo

Astro x tRPC 🚀

End-to-end typesafe APIs in Astro wesbites made easy

astro-trpc licence astro-trpc forks astro-trpc stars astro-trprc issues astro-trpc pull-requests

View Demo · Report Bug · Request Feature

👋 Introducing astro-trpc

astro-trpc is a tRPC adapter allowing you to easily build typesafe APIs in Astro. No code generation, run-time bloat, or build pipeline.

🚀 Demo

Try out the minimal demo. We hope you enjoy it.

Open in StackBlitz

Many Thanks to all the Stargazers who have supported this project with stars()

Stargazers repo roster for astro-trpc

Basic file structure

Your file structure should look something like this:

├── astro.config.mjs
├── package.json
├── public
│   └── favicon.svg
├── src
│   ├── env.d.ts
│   ├── lib
│   │   └── trpcClient.ts
│   └── pages
│       ├── api
│       │   └── trpc
│       │       └── [trpc].ts
│       └── index.astro
└── tsconfig.json

💻 Quickstart

To get started, install astro-trpc and @trpc/client with your favourite package manager

# Using NPM
npm install astro-trpc @trpc/client

# Using Yarn
yarn add astro-trpc @trpc/client

# Using PNPM
pnpm install astro-trpc @trpc/client

Note: If you want to use zod for input validation - which we we'll use in this introduction - make sure you have enabled strict mode in your tsconfig.json

How to use

First, let's create our router in our tRPC endpoint, we will use zod for validation but you don't have to. For that, we will create a [trpc].ts file in the pages/api/trpc folder:

// [trpc].ts
import { createAstroTRPCApiHandler } from 'astro-trpc';
import * as trpc from '@trpc/server';
import { z } from 'zod';

// the tRPC router
export const appRouter = trpc.router().query('greeting', {
    input: z
        .object({
            name: z.string().nullish(),
        })
        .nullish(),
    resolve({ input }) {
        return {
            greeting: `hello ${input?.name ?? 'world!'}`,
        };
    },
});

// type definition of the router
export type AppRouter = typeof appRouter;

// API handler
export const all = createAstroTRPCApiHandler({
    router: appRouter,
    createContext: () => null,
});

Now, let's create our client. We'll create a trpcClient.ts file in pages/lib

// trpcClient.ts
import { createTRPCClient } from '@trpc/client';
import type { AppRouter } from '../pages/api/trpc/[trpc]';

export const client = createTRPCClient<AppRouter>({
    url: process.env.NODE_ENV === 'production'
            ? import.meta.env.TRPC_ENDPOINT_URL
            : `http://localhost:3000/api/trpc`,
});


Now that we're set up, we can start consuming our API. Let's see it in action:

// index.astro
---
import { client } from '../lib/trpcClient';

const data = await client.query("greeting", {name: "Astro 🚀"});
---

<meta charset="utf-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<title>astro-trpc demo</title>

<body>
  <p> {data.greeting} </p>
</body>

You can notice the autocompletion you get when using the client and also errors when you provide the wrong types to the API or query an inexisting route. Demonstration

Now let's start the dev server to see our changes Hello Astro 🚀

You can now enjoy the full power of tRPC in Astro 👏 !

💡 Inspired by

🛡️ License

This project is licensed under the MIT License - see the LICENSE file for details.

If you find something is missing, we're listening listening. Please create a feature request from here.

🤝 Contributing to astro-trpc

Any kind of positive contribution is welcome! Please help us improve this project by contributing.

🙏 Support

Before you move away, please give this project a ⭐️ if you liked it. That's the best way you can show your support


This project follows the all-contributors specification. Contributions of any kind welcome!

You might also like...

Auto-import components in Astro projects

Astro Auto Import 🔗 Looking for the main package? Jump to astro-auto-import → 🚀 Project Structure This project uses workspaces to develop a single p

Dec 30, 2022

🖼️ Bringing Material Design 3 to the Astro Blog. [WIP]

🖼️ Gumori You [WIP] Bringing Material Design 3 to the Astro Blog. 👥 Contributing If you're interested in contributing to Gumori You, pls read the fo

Oct 16, 2022

🚀 A (still experimental) Lyra integration for Astro

Lyra's Astro Plugin This package is a (still experimental) Lyra integration for Astro. Usage Configuring the Astro integration // In `astro.config.mjs

Dec 13, 2022

Render arbitrary Markdown content in Astro, optionally integrating with any existing configuration.

Astro Markdown Astro Markdown lets you render arbitrary Markdown content in Astro, optionally integrating with any existing configuration. --- import

Dec 22, 2022

A plugin for creating hierarchical navigation in Astro projects. Supports breadcrumbs too!

astro-navigation A plugin for creating hierarchical navigation in Astro projects. Supports breadcrumbs too! Full docs coming soon! Basic usage This pa

Dec 19, 2022

Type-safe session for all Astro SSR project

Astro Session Why use Astro Session? When building server application with Astro, you will often need session system to identify request coming from t

Dec 19, 2022

Website to present projects made by me and that are part of my personal portfolio. It was made using React, HTML y Scss (CSS).

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

Dec 23, 2021

A showcase of problems once hard or impossible to solve with CSS alone, now made trivially easy with Flexbox.

Solved by Flexbox A showcase of problems once hard or impossible to solve with CSS alone, now made trivially easy with Flexbox. View Site Viewing the

Jan 2, 2023

Installing husky made easy as woof!

auto-husky Installing husky made easy as woof! 🐶 📑 Table of contents 💾 Installation 🔰 Usage 🔢 Versioning 💾 Installation You can install the pack

Jun 28, 2022
Comments
  • Not working with trpc version 10

    Not working with trpc version 10

    Hi, first of all thank you for this package!

    TRPC has gone under some breaking changes in v10, and they just moved to a flat 10.0.0 from rc-9 so far.

    I tried fixing some things such as some imports have been shifted around but couldn't grok it.

    Would you be updating this package for v10?

    opened by unbiased-dev 6
  • [ci] release

    [ci] release

    This PR was opened by the Changesets release GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to master, this PR will be updated.

    Releases

    [email protected]

    Patch Changes

    opened by github-actions[bot] 0
Releases(v0.3.2)
Owner
Happydev
Happydev
Examples of using various CSS-in-JS libs in Astro (repo for withastro/astro#4432)

astro + css-in-js This monorepo will show examples of various CSS-in-JS libraries in Astro. Currently only shows a basic counter example, would be nic

Mayank 15 Dec 18, 2022
TypeSafe MongoDB Atlas Data API SDK for Deno & Deno Deploy

Atlas SDK atlas_sdk is a TypeSafe MongoDB Atlas Data API SDK for Deno & Deno Deploy Links Docs Import Replace LATEST_VERSION with current latest versi

Erfan Safari 20 Dec 26, 2022
typesafe nodejs client for transit.land

TransitLand Graphql Client About Since the Transitland released its new and shiny GraphQL API, it is possible to query the API using GraphQL. The clie

ioki 5 Jan 9, 2023
Typesafe API for processing iterable data in TypeScript and JavaScript.

Stream API Type-safe API for processing iterable data in TypeScript and JavaScript similarly to Java 8 Stream API, LINQ or Kotlin Sequences. Unlike Rx

Norbert Szilagyi 31 Aug 4, 2022
Quick T3 Stack with SvelteKit for rapid deployment of highly performant typesafe web apps.

create-t3svelte-app Just Build npx create-t3svelte-app Outline Get Building npm yarn More Info ?? Early Version Note Prisma Requirements Available Tem

Zach 85 Dec 26, 2022
End-to-End type safety for REST APIs written in Fastify. Only problem is you have to explicity export and register route handlers. LOL

Chino intelligence in japaneese End-to-End type safety for REST APIs written in Fastify. Only problem is you have to explicity export and register rou

sambit sahoo 2 Sep 12, 2022
A tiny script and component intended to be used with Astro for generating images with eleventy-img.

Astro + eleventy-img A tiny script and component intended to be used with Astro for generating images with eleventy-img. It also supports creating blu

Erika 36 Dec 16, 2022
Astro 1.0 Hackathon submission

title published description tags cover_image Trying out Astro SSR & Astro 1.0 Hackaton false astro, ssr, webcomponents, hackathon https://imgur.com/lV

Pascal Schilp 26 Jan 2, 2023
🦔 AstroJS GoogleChromeLabs critters integration. Inline your critical CSS with Astro.

astro-critters ?? This Astro integration brings critters to your Astro project. Critters is a plugin that inlines your app's critical CSS and lazy-loa

Nikola Hristov 33 Dec 11, 2022
Make an Astro site with content from Notion (and more)

Astronotion ⚠️ It is strongly recommended to upgrade to 0.0.7 (what has been fixed?) npm install -D astronotion@latest (or other package managers' equ

Eka 14 Dec 19, 2022