Skip to content
This repository has been archived by the owner on Dec 10, 2022. It is now read-only.

Latest commit

 

History

History
225 lines (175 loc) · 8.23 KB

README.md

File metadata and controls

225 lines (175 loc) · 8.23 KB

Warning

This package is deprecated because tRPC v10 implemented new feature that made it easy to use inside of Astro, noticably the new fetch adapter. We thank you for being part of this project and hope to see you in the future :)

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 astro-trpc total downloads

View Demo · Report Bug · Request Feature

Table of contents

👋 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.

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

Stargazers repo roster for astro-trpc

🚀 Demo

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

Open in StackBlitz

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!