Quick T3 Stack with SvelteKit for rapid deployment of highly performant typesafe web apps.

Overview

T3-SvelteKit

create-t3svelte-app

NPM version License Stars Downloads


Just Build
npx create-t3svelte-app

Outline

Get Building

✅ Elegant full-stack framework powered by SvelteKit
✅ Static typing support with TypeScript
✅ End-to-end typesafe APIs with tRPC
✅ Enjoyable database interaction with Prisma
✅ Efficient styling with Tailwind CSS

npm

npx create-t3svelte-app@latest

yarn

yarn create t3svelte-app

More Info 🛠

Early Version Note

This initial version is lacking significant polish that I hope to add in a new release shortly, including:

  • Less Opinions, More Customization (including prettier/eslint not as forced defaults)
  • SQLite as schema.prisma default ✅
  • Helper comments
  • Package Manager Support

Prisma Requirements

If you choose not to init DB on first build, you can initialize prisma db at any time by editing the DATABASE_URL in .env and then running npx prisma db pull and npx prisma generate. You can read more about Prisma on their docs.

Available Templates

A simple CLI with highly opinionated, out-of-the-box ready SvelteKit/tRPC/Prisma/Tailwind application. CLI options include 'Standard' and 'Standard + UI Extras' (customization soon). Just run and start building.

Standard

  • SvelteKit
  • tRPC - preconfigured with example API call in +page.svelte
  • Tailwind CSS - preconfigured with eslint/prettier & 'tailwind prettier plugin' integration
  • Prisma ORM - CLI option to initialize DB on run - no need to run prisma db pull or prisma db generate

Standard + UI Extras

  • Standard
  • Headless UI
  • HeroIcons

Contributing

See a bug? Want to help? Easiest way is to clone the main repo and run npm link in the cloned directory. You can code and then run create-t3svelte-app in any directory.

git clone https://github.com/zach-hopkins/create-t3svelte-app
cd create-t3svelte-app
npm i
npm link
mkdir test-project
cd test-project
create-t3svelte-app

Run npm unlink create-t3svelte-app to undo.

Caveats & Addendums

Server-Side Rendering

If you need to use the tRPC client in SvelteKit's load() function for SSR, make sure to initialize it like so:

// $lib/trpcClient.ts

import { browser } from '$app/env';
import type { Router } from '$lib/trpcServer';
import * as trpc from '@trpc/client';
import type { LoadEvent } from "@sveltejs/kit";

const url = browser ? '/trpc' : 'http://localhost:3000/trpc';
export default (loadFetch?: LoadEvent['fetch']) =>
  trpc.createTRPCClient<Router>({
    url: loadFetch ? '/trpc' : url,
    transformer: trpcTransformer,
    ...(loadFetch && { fetch: loadFetch as typeof fetch })
  });
  

Then use it like so:

// src/routes/+authors.svelte

import trpcClient from '$lib/trpcClient';
import type { Load } from '@sveltejs/kit';

export const load: Load = async ({ fetch }) => { // 👈 make sure to pass in this fetch, not the global fetch
	const authors = await trpcClient(fetch).query('authors:browse', {
		genre: 'fantasy',
	});
	return { props: { authors } };
};

Vercel's Edge Cache for Serverless Functions

Your server responses must satisfy some criteria in order for them to be cached on Vercel's Edge Network. tRPC's responseMeta() comes in handy here since you can initialize your handle in src/hooks.server.ts like so:

// src/hooks.server.ts

import { router } from '$lib/trpcServer';
import { createTRPCHandle } from 'trpc-sveltekit';

export const handle = async ({ event, resolve }) => {
  const response = await createTRPCHandle({
    url: '/trpc',
    event,
    resolve,
    responseMeta({ type, errors }) {
      if (type === 'query' && errors.length === 0) {
        const ONE_DAY_IN_SECONDS = 60 * 60 * 24;
        return {
          headers: {
            'cache-control': `s-maxage=1, stale-while-revalidate=${ONE_DAY_IN_SECONDS}`
          }
        };
      }
      return {};
    }
  });

  return response;
};

Shoutouts

License

MIT

Comments
  • feat: detect user package manager and use it instead of npm

    feat: detect user package manager and use it instead of npm

    Pertains to #22. This PR implements the function from create-t3-app to detect which package manager is being used by the user and updates the compileInstalls function and Install dependencies task in createT3SvelteApp to use the same.

    ~~NOTE: This works with both npm and pnpm but has not been tested with yarn yet. I don't really know how to test it with yarn locally without pushing the package to npm... Any feedback on this is appreciated.~~

    EDIT: Never mind, tested with yarn as well. Works as intended.

    opened by vishalbalaji 2
  • 'Undefined' error on default options on Mac

    'Undefined' error on default options on Mac

    ? Please choose which project template to use Standard
    ? Initialize a git repository? No
    ? Automatically install dependencies? No
    ? Initialize Postgres DB w/ Prisma? (Requires DB URI String) No
    
    file:///Users/mac-suer/.npm/_npx/5be47aec1dfa4302/node_modules/create-t3svelte-app/src/cli.js:98
          dbString: '' || dbAnswers.dbString
                                    ^
    
    TypeError: Cannot read properties of undefined (reading 'dbString')
        at promptForMissingOptions (file:///Users/ajcwebdev/.npm/_npx/5be47aec1dfa4302/node_modules/create-t3svelte-app/src/cli.js:98:33)
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at async cli (file:///Users/ajcwebdev/.npm/_npx/5be47aec1dfa4302/node_modules/create-t3svelte-app/src/cli.js:104:16)
    

    Can't reproduce in linux - could have something to do with null string in the object:

    if (answers.db && requireURI) 
      var dbAnswers = await inquirer.prompt(dbQuestions)
    
    //Handle Empty Options
    else var dbAnswers = {dbString: ''}
    if (!dbSolutionAnswers) var dbSolutionAnswers = {dbSolution: ''}
    

    Can dig into this a little later, probably something stupid

    opened by zach-hopkins 2
  • Updated Vite version in templates

    Updated Vite version in templates

    When running npx create-t3svelte-app I got an error while installing dependencies. I bumped Vite's version to ^4.0.0 and seems like that fixed the issue.

    opened by L-Mario564 1
  • Error when trying to run this project

    Error when trying to run this project

    Not sure what to say - when I build this with

    npx create-t3svelte-app@latest  
    

    ( Windows 10)

    I receive the following :

    VITE v3.2.5  ready in 1963 ms
    
      ➜  Local:   http://localhost:5174/
      ➜  Network: use --host to expose
    file:///C:/test2/node_modules/@sveltejs/kit/src/exports/node/index.js:108
            const headers = Object.fromEntries(response.headers);
                                   ^
    
    TypeError: undefined is not iterable
        at Function.fromEntries (<anonymous>)
        at setResponse (file:///C:/test2/node_modules/@sveltejs/kit/src/exports/node/index.js:108:25)
        at file:///C:/test2/node_modules/@sveltejs/kit/src/exports/vite/dev/index.js:523:6
    
    Node.js v18.12.1
    

    highlighting line 523 here:

    				if (rendered.status === 404) {
    					// @ts-expect-error
    					serve_static_middleware.handle(req, res, () => {
    						setResponse(res, rendered);
    					});
    				} else {
    >>>>>                          setResponse(res, rendered);
    				}
    			} catch (e) {
    				const error = coalesce_to_error(e);
    				res.statusCode = 500;
    				res.end(fix_stack_trace(error));
    			}
    		});
    	};
    }
    

    (Seems to happen regardless of project configuration options, both with/without db config. I am trying to create a typescript + tRPC + Prisma configuration

    opened by jesslawnz 1
  • fix: pin tRPC version to 9.27.* to correspond with trpc-sveltekit

    fix: pin tRPC version to 9.27.* to correspond with trpc-sveltekit

    Pertains to #23. Currently, the RPC client and server in templates/trpc/package.json and templates/prisma_trpc/package.json have no specified versions, causing initial package.json creation to fail when installed in conjuction with trpc-sveltekit. This PR simply pins the versions to ^9.27.2 in both these files.

    There is currently a PR open in trpc-sveltekit to update it to be compatible with tRPC 10, but this fixes this issue for now.

    opened by vishalbalaji 1
  • Initialization failed

    Initialization failed

    Right after selecting all the options, the project fails to initialize with the following error

    Copy project files
        → npm ERR!     /home/jerric/.npm/_logs/2022-11-02T07_09_10_963Z-debug-0.log
        Initialize git
        Install dependencies
        Initialize DB
    node:child_process:399
          ex = new Error('Command failed: ' + cmd + '\n' + stderr);
               ^
    
    Error: Command failed: npm install --save --package-lock-only --no-package-lock @trpc/client @trpc/server trpc-sveltekit trpc-transformer zod && npm install --save -D --package-lock-only --no-package-lock @prisma/client prisma
    npm ERR! code ERESOLVE
    npm ERR! ERESOLVE could not resolve
    npm ERR!
    npm ERR! While resolving: [email protected]
    npm ERR! Found: @trpc/[email protected]
    npm ERR! node_modules/@trpc/server
    npm ERR!   @trpc/server@"*" from the root project
    npm ERR!   peer @trpc/server@"10.0.0-rc.3" from @trpc/[email protected]
    npm ERR!   node_modules/@trpc/client
    npm ERR!     @trpc/client@"*" from the root project
    npm ERR!
    npm ERR! Could not resolve dependency:
    npm ERR! trpc-sveltekit@"*" from the root project
    npm ERR!
    npm ERR! Conflicting peer dependency: @trpc/[email protected]
    npm ERR! node_modules/@trpc/server
    npm ERR!   peer @trpc/server@"^9.27.4" from [email protected]
    npm ERR!   node_modules/trpc-sveltekit
    npm ERR!     trpc-sveltekit@"*" from the root project
    npm ERR!
    npm ERR! Fix the upstream dependency conflict, or retry
    npm ERR! this command with --force, or --legacy-peer-deps
    npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
    npm ERR!
    npm ERR! See /home/jerric/.npm/eresolve-report.txt for a full report.
    
    npm ERR! A complete log of this run can be found in:
    npm ERR!     /home/jerric/.npm/_logs/2022-11-02T07_09_10_963Z-debug-0.log
    
        at ChildProcess.exithandler (node:child_process:399:12)
        at ChildProcess.emit (node:events:526:28)
        at maybeClose (node:internal/child_process:1090:16)
        at Process.ChildProcess._handle.onexit (node:internal/child_process:302:5) {
      killed: false,
      code: 1,
      signal: null,
      cmd: 'npm install --save --package-lock-only --no-package-lock @trpc/client @trpc/server trpc-sveltekit trpc-transformer zod && npm install --save -D --package-lock-only --no-package-lock @prisma/client prisma',
      context: [Object: null prototype] {}
    }
    
    Node.js v17.5.0
    
    opened by jerriclynsjohn 1
  • Always uses npm to install dependencies

    Always uses npm to install dependencies

    I use pnpm rather than npm, but despite using pnpx create-t3svelte-app, it always uses npm to install dependencies.

    I'm unsure if there's a way to detect which package manager that is being used, but either that or a new step that asks which package manager you're using when installing dependencies would be ideal.

    Not super important as you can just deselect "auto install dependencies" and do it myself though.

    opened by megadrive 1
  • Windows: Invalid template path

    Windows: Invalid template path

    The template path is invalid, seems to prepend an additional host drive letter at the beginning. Not working for NPM and PNPM, unsure about others.

    PS C:\Users\...\dev> npx create-t3svelte-app@latest
    ? Please choose which project template to use Standard + UI Extras
    ? Initialize a git repository? No
    ? Automatically install dependencies? No
    ? Configure Database? (N = SQLite Template) No
    C:\C:\Users\...\AppData\Local\npm-cache\_npx\5be47aec1dfa4302\node_modules\create-t3svelte-app\templates\standard + ui extras
    ERROR Invalid template name
    
    opened by megadrive 1
  • Error when skipping DB setup

    Error when skipping DB setup

    https://github.com/zach-hopkins/create-t3svelte-app/blob/f46cb3bbb0e3ccb7bcfebc6f7a55bbac7b6029b2/src/cli.js#L118

    https://github.com/zach-hopkins/create-t3svelte-app/blob/f46cb3bbb0e3ccb7bcfebc6f7a55bbac7b6029b2/src/cli.js#L127

    The second line breaks the CLI because dbAnswers is initialized as a list, not an object.

    opened by Lootwig 1
  • Adding SvelteKit Auth/Auth.js to the main stack

    Adding SvelteKit Auth/Auth.js to the main stack

    Implementing Vercel's official auth solution for SvelteKit.

    Checklist

    • [x] Auth.js (as a standalone package)
    • [x] Auth.js + Prisma
    • [ ] Auth.js + Prisma + tRPC
    • [ ] Update README with information about this package
    opened by L-Mario564 0
  • Thoughts on implementing SvelteKit Auth?

    Thoughts on implementing SvelteKit Auth?

    Vercel recently brought their NextAuth package to SvelteKit. Adding an auth solution would be great and was wondering if there are any plans to add this to the stack.

    opened by L-Mario564 3
  • Why it doesn't have the first step to create the project directory?

    Why it doesn't have the first step to create the project directory?

    It feels, to me, that we are missing the first step. Where the CLI ask the name of the project to create the directory and set that name everywhere.

    There a reason why this package skips it? Do you want help to add it?

    opened by enBonnet 1
Owner
Zach
Full stack developer. C# | Python | JS | Vue | Svelte | React
Zach
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

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

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
This is a full-stack exercise tracker web application built using the MERN (MongoDB, ExpressJS, ReactJS, NodeJS) stack. You can easily track your exercises with this Full-Stack Web Application.

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

WMouton 2 Dec 25, 2021
A Web UI toolkit for creating rapid prototypes, experiments and proof of concept projects.

MinimalComps2 A Web UI tookkit for creating rapid prototypes, experiments and proof of concept projects. The site: https://www.minimalcomps2.com/ Full

Keith Peters 32 Apr 18, 2022
The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling rapid development of iofod extensions through the SDK.

iofod-sdk English | 简体中文 The iofod SDK provides developers with the ability to interact with the main iofod interface within the Web worker, enabling

iofod, Inc. 47 Oct 17, 2022
Scaffold a full-stack SvelteKit application with tRPC and WindiCSS out of the box

create-sweet-app Interactive CLI to quickly set up an opinionated, full-stack, typesafe SvelteKit project. Inspired by the T3 Stack and create-t3-app

David HrabÄ› 10 Dec 16, 2022
A set of tools, helping you building efficient apps in a fast way. >> SvelteKit & GraphQL <<

KitQL KitQL, A set of tools, helping you building efficient apps in a fast way. ?? Infos Documentation: https://kitql.vercel.app/ Day by day progress,

JYC 262 Dec 27, 2022
Litebug is a rapid data entry interface for Firefly iii

Litebug is a rapid data entry interface for Firefly iii.

Amjad Mohamed 2 Nov 7, 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
End-to-end typesafe APIs in Astro wesbites made easy

Astro x tRPC ?? End-to-end typesafe APIs in Astro wesbites made easy View Demo · Report Bug · Request Feature ?? Introducing astro-trpc astro-trpc is

Happydev 61 Dec 30, 2022
injects Chromium extension into packaged electron apps. highly experimental. might work.

Electron extension injector injects Chromium extension into packaged electron apps. highly experimental. might work. use Alt+Shift+E to access extensi

Cynthia 6 Sep 2, 2022
a quick start boilerplate for developing web3 apps and deploying smart contracts.

create-web3 A boilerplate for starting a web3 project. This boilerplate quickly creates a mono repo with 2 environments, a Next JS environment for fro

Eric Roupe 83 Dec 16, 2022
A low-feature, dependency-free and performant test runner inspired by Rust and Deno

minitest A low-feature, dependency-free and performant test runner inspired by Rust and Deno Simplicity: Use the mt test runner with the test function

Sondre Aasemoen 4 Nov 12, 2022
Lightweight (< 2.3kB gzipped) and performant natural sorting of arrays and collections by differentiating between unicode characters, numbers, dates, etc.

fast-natural-order-by Lightweight (< 2.3kB gzipped) and performant natural sorting of arrays and collections by differentiating between unicode charac

Shelf 5 Nov 14, 2022
A lightweight, performant, and simple-to-use wrapper component to stick section headers to the top when scrolling brings them to top

A lightweight, performant, and simple-to-use wrapper component to stick section headers to the top when scrolling brings them to top

Mayank 7 Jun 27, 2022
Performant WebSocket Server & Client

Socketich ?? Performant WebSocket server and persistent client powered by uWebSockets.js and PersistentWebSocket Install npm i @geut/socketich Usage S

GEUT 6 Aug 15, 2022