A First Look at create-t3-app
Published:
create-t3-app is a fullstack, typesafe React framework with Next.js, tRPC, Prisma, and Tailwind deployed on Vercel and Fly.
Outline
- Introduction
- Create t3 App
- Provision PostgreSQL Database
- Query Posts with tRPC
- Add Cells for Declarative Data Fetching
- Deployment
- Resources, Articles, and Videos
All of this project’s code can be found in the First Look monorepo on my GitHub.
Introduction
create-t3-app
is a fullstack React framework and CLI that has emerged as an evolution of the T3 stack recommended on Theo Browne’s website init.tips
. It’s described by its creators as “kind of a template,” which is meant to stress that it is “NOT a template”.
Why the t3 Stack Was Created
ct3a
’s goal is to provide the quickest way to start a new fullstack, typesafe web application. To achieve this goal, the stack is architected around three foundational constituents that together can be bundled together and used to develop monolithic applications:
- Typed React frontend (TypeScript and Next.js)
- Typed database client (Prisma)
- Typed remote procedure calls (tRPC)
Depending on your background and perspective that may sound like a ground breaking innovation, a completely obvious repackaging of techniques used over two decades ago, or an absolute heresy because you’ve been taught that developing monoliths is a sin.
Source: Sabin Adams - End-To-End Type Safety
As someone who has resisted TypeScript until now, this is terrifying to me. But I’m going to make an exception and embrace TypeScript for the first time in my life if this stack can actually provide a smooth and streamlined TypeScript experience.
But for those already in love with TypeScript and fullstack React frameworks, you are probably feeling a strange sense of deja-vu right now. This is an almost identical stack to Blitz.js and shares many of the same architectural principles. The notable difference is that CTA includes tRPC (which itself has frequently been compared to Blitz.js).
History of the t3 Stack and Create Nex App
The first iteration of the init.tips
site suggested only one command was needed to initialize a mostly optimal boilerplate for the majority of web applications in 2021. This suggestion (in its infinite wisdom) was: Create a Next.js app, but with TypeScript.
As people began to consider this advice, many developers inevitably asked:
“Mmmm, but what about all that other stuff not included in this stack that I need to make an even borderline functional application?”
This lead to other recommendations for add-ons to the stack. These add-ons targeted specific use cases such as:
- Prisma for managing database migrations and SQL queries through an ORM
- Next-auth for client side authentication
- Tailwind for CSS and UI styling
- tRPC for end-to-end typesafe APIs
If these were being frequently recommended, it stood to reason that it would make sense to create a new, more full featured command. This would generate not only a typed Next.js project, but one with an ORM, authentication, styling, and API protocol.
These would be automatically included while also giving you the ability to opt out if you still want the bare-bones version. I’m happy that this is taking off and that some consider it a novel idea.
I’ve spent the last two years relentlessly promoting frameworks assembling different versions of these kinds of stacks. RedwoodJS, Blitz.js, and Bison all have extremely similar but also slightly different stacks. To understand how these relate to each other, I would break it down like so:
This is not meant to be an exhaustive list and I’ve purposefully left off things like tests, mocks, Storybook, deployment, and other non-architectural pieces.
As the project has evolved from init.tips
to create-t3-app
, it has taken on a life of its own. Theo has stated numerous times that he did not actually initiate the creation of create-t3-app
, he simply talked about the idea numerous times in public.
In fact, he never would have had the time to build or manage such a project. On top of full time content creation, he’s the CEO of a startup building ping.gg, a collaborative streaming tool. His influence over the project primarily stemmed from his various public discussions of the stack.
These discussions inspired a group of people who were members of his recently formed Discord server. This online space was created to bring together fans of his Twitch and YouTube channels. A group independently began building out a full fledged project. This activity was centered around the work of Shoubhit Dash.
Known as nexxel or nexxeln online, Shoubhit took the initiative to formalize the stack by developing an interactive CLI tool that would be able to scaffold out a project using arbitrary combinations of the various technologies used in the stack. nexxel, a 17 year old self-taught developer, is the true rosetta stone to this project.
Nexxel was blogging about tRPC in May right before launching the framework. Build end to end typesafe APIs with tRPC signaled the birth of the framework on May 21, 2022 along with an initial commit on May 20, 2022. Originally called Create Nex App, the README described the project like so:
Scaffold a starting project using the t3 stack using this interactive CLI.
The early prototypes of the project included Next.js, Tailwind, and TypeScript along with tRPC. Throughout June, the project began attracting around a dozen contributors. Julius Marminge (juliusmarminge) was one of the earliest contributors and remains active today.
Roughly a month later on June 26, 2022, nexxel published T3 stack and my most popular open source project ever. This blog post was published after working with the other contributors to fully integrate Prisma and Next Auth, marking the completion of the stack’s initial integration phase.
Throughout the month of June, the GitHub repo gained nearly 2,000 GitHub stars. Despite having only been created at the end of May, the project had reached nearly unprecedented levels of momentum. On July 17, 2022, nexxel migrated his personal blog to create-t3-app and by the middle of August the project had over 5,000 stars.
Create t3 App
To get started with ct3a
, you can run any of the following three commands and answer the command prompt questions:
The following CLI options are currently available:
Option | Description |
---|---|
--noGit | Explicitly tell the CLI to not initialize a new git repo in the project |
-y , --default | Bypass CLI and use all default options to bootstrap new t3-app |
[dir] | Include a directory argument with a name for the project |
--noInstall | Generate project without installing dependencies |
We’ll give our project a name and select all available options with the exception of NextAuth.
I will select the following options:
Including the -y
option will select the default configuration which bundles all four packages into the project. The interactive CLI prompt will also ask whether you want to use JavaScript or TypeScript. If you try to select JavaScript though, you will discover that the option is but a mere illusion. In fact, you must use TypeScript and also there is no God.
Enter your project directory and start the development server.
Open localhost:3000 to see the generated project.
Project Structure
If we ignore the configuration files in the root of our project then our folder and file structure includes the following:
We’ll break down each of these different directories and files as we progress through the tutorial. But as a quick overview, we’ll be primarily working with:
- Pages and API Routes
src/pages/index.tsx
src/pages/api/examples.ts
src/pages/api/trpc/[trpc].ts
- Server and Database
src/server/db/client.ts
src/server/trpc/context.ts
src/server/trpc/router/_app.ts
src/server/trpc/router/example.ts
src/server/trpc/trpc.ts
- Styling
src/styles/globals.css
- Utilities
src/utils/trpc.ts
Tailwind Styles
Open src/pages/index.tsx
and make some changes to customize the home page. Feel free to follow along or make your own alterations, there are many different ways this project could be organized. First, I will create a file called file called home-styles.ts
to hold all styling that will be used on the home page of the website.
I will export a variable defining each Tailwind style that can be reused throughout the project.
appContainer
styles themain
contenttitle
styles the page’sh1
headerpurple
styles T3 with its signature purple colorbody
styles thep
tag introducing the list of technologies included in the stackgrid
styles thediv
wrapping theTechnologyCard
componentsqueryResponse
styles thediv
wrapping the tRPChello
query
Add these style variables to the Home
component.
Add style variables to the TechnologyCard
component:
cardSection
styles the card’s container on thesection
elementcardTitle
styles the technology’s title on each cardcardDescription
styles the description of each technologylink
styles the link on each card
Now I will modify the four cards to include links to my blog and social media profiles. With that change in mind, I will use url
instead of documentation
for a more appropriate prop name. I will also change the links to include the entire card within the anchor tags so clicking anywhere on the card will open the hyperlink.
Return to localhost:3000 to see the changes.
Lastly, I will abstract out the TechnologyCard
component into its own file and rename it to Card
.
Rename TechnologyCardProps
to CardProps
and create a Card
component.
Import Card
into src/pages/index.tsx
and remove CardProps
.
Provision PostgreSQL Database
Since this a fullstack framework, it already includes a tool called Prisma for working with our database. Our models will be defined in the prisma/schema.prisma
file along with our specific database provider.
Add Posts Model to Prisma Schema
The initial generated project has the database datasource
set to SQLite. Since we want to use a real database, open schema.prisma
and update the datasource
to the PostgreSQL provider.
In addition to the current models in the schema, add a Post
model with an id
, title
, description
, body
, and createdAt
timestamp.
Also, uncomment all appearances of @db.Text
on the Account
model.
Initialize Railway Database and Run Migration
We’ll use Railway to provision a PostgreSQL database. First, you need to create a Railway account and install the Railway CLI. If you are unable to login through the browser, run railway login --browserless
instead.
Run the following command, select “Empty Project,” and give your project a name.
To provision the database, add a plugin to your Railway project and select PostgreSQL.
Set the DATABASE_URL
environment variable for your database and create a .env
file to hold it.
Run a migration with prisma migrate dev
to generate the folders and files necessary to create a new migration. We’ll name our migration init
with the --name
argument.
After the migration is complete, generate the Prisma client with prisma generate
.
Seed a Blog Post
Right now we’ll avoid implementing an endpoint through our app with write, update, or delete functionality since we’ll not be including authentication in this section. However, there are at least five different ways you can write data to your database. If you want to skip this section, the tl;dr is send raw SQL queries through the Railway Query dashboard.
The Railway dashboard provides three separate methods for accessing your database (not including using the connection string itself as an environment variable in the project as we’ll do later):
- Execute raw SQL queries under the Query tab
- Connect to database with the
psql
command under the Connect tab - Enter data with Railway’s UI under the Data tab
For Prisma, you can either:
- Login to the Prisma Data Platform at cloud.prisma.io
- Run Prisma Studio on localhost 5555 with
pnpm prisma studio
Note: I’m including Prisma Studio here for completion’s sake, but I advise against using it. It’s a seemingly sleek and polished product with a very strange input bug that causes it to throw out a value if you don’t click away from the input before adding the record to the table. This means you can create a record and have a crucial field get totally wiped and replaced with a blank value.
Yes, this is should just be for a test database, and yes it’s just dummy data. But still, to me, especially for a database tool, this seems fundamentally broken and I honestly can’t recommend using this tool in good conscious. I first experienced this bug around the end of 2021 and you can view a recording of the bug in action on an episode of Teach Jenn Tech recorded in November 2022.
GUIs are more intuitive for developers without much SQL experience. But unfortunately, they can also be buggy or cumbersome. You especially don’t want to be entering every row by hand when you need to input large amounts of data at once. SQL commands provide a more consistent and scalable technique for seeding a database or entering ongoing new data.
The first option on the list (execute raw SQL queries under the Query tab on Railway’s dashboard) gives us the best of both worlds. It does not require entering data into any GUI but it also does not require installing a Postgres client like psql
to your local machine and connecting to a database instance over the network. We could create a blog post with the following command:
This SQL command can be entered directly into the text area under the Query tab.
Click “Run query” and then add two more blog posts:
Query Posts with tRPC
tRPC is a library that is designed for writing typesafe APIs. Instead of importing server code, the client only imports a single TypeScript type. tRPC transforms this type into a fully typesafe client that can be called from the frontend.
Create Post Router
Create a file to initialize a router instance called postRouter
. This will query for all of our posts.
Add a query endpoint to the router with the .query()
method. It with accept two arguments: name
for the name of the endpoint and params
for query parameters.
params.resolve
implements the endpoint which will be a function with a single req
argument that runs the Prisma Client findMany
query which returns a list of records, in this case all
posts based on the post
model.
params.input
provides input validation and will be discussed in the Create Default Query Cell section.
Create App Router
In src/server/router/index.ts
, there is a base appRouter
for our server entry point. This can be gradually extended with more types and resolved into a single object.
Import postRouter
and use the .merge()
method to combine the following three routes into a single appRouter
instance:
exampleRouter
postRouter
protectedExampleRouter
Queries related to blog posts will be prefixed with post
(post.all
, post.byId
). The hello query example will be prefixed with example
as seen earlier with example.hello
.
Query Posts with useQuery
Open src/pages/index.tsx
to query all posts and display them on the home page. Create a Posts
component and initialize a variable called postsQuery
above the return statement. Set the postsQuery
variable to the output of post.all
with the useQuery()
hook.
As mentioned in the previous section, the appRouter
object can be inferred on the client. Stringify the JSON output from postsQuery.data
and display the data below the title of the page.
Return Posts
in the Home
component.
We have some conditional logic to ensure that a loading message is displayed if the data has not yet returned from the server. But what if there are no blog posts in the database or the server returns an error? This is a case that would be perfectly suited for a Cell.
Add Cells for Declarative Data Fetching
One of my favorite patterns from Redwood that I have been hoping to see in other frameworks is the concept of a Cell. Cells provide a built-in convention for declarative data fetching that isn’t exactly a state machine but shares common benefits and characteristics.
Unlike general purpose finite-state machines, Cells are specifically focused on common data fetching outcomes. They give developers the ability to avoid writing any conditional logic since a cell will manage what happens during the following four potential states of your data fetching:
- Success - Display the response data
- Failure - Handle the error message and provide instructions to the user
- Empty - Show a message or graphic communicating an empty list
- Loading - Show a message or graphic communicating the data is still loading
Thankfully, my hopes were fulfilled when lead tRPC maintainer, Alex Johansson opened a PR with a tRPC Cell example that he acknowledged was influenced by RedwoodJS.
Create Default Query Cell
createQueryCell
is used to bootstrap DefaultQueryCell
which can be used anywhere in your application.
Ideally this will one day be internal to either tRPC or create-t3-app
and you’ll be able to just write cells without thinking about it. But for now, we need to create this ourselves.
We want to be able to query an individual blog post based on its id
. Create a post
page with a dynamic route based on the id
.
Since we’ll be sending data to the database, we need to validate the input
. zod
is a TypeScript schema validator with static type inference. We’ll also import TRPCError
for error handling.
Add byId
query to Post router in src/server/router/post.ts
and destructure the id
from the input
.
findUnique
query lets you retrieve a single database record based on the id
provided by passing it to Prisma’s where
option.
Last but not least, throw an error with TRPCError
if a post is not returned.
Create Post Page
Import DefaultQueryCell
in src/pages/post/[id].tsx
and create a component called PostPage
.
Return DefaultQueryCell
and pass postQuery
to query
and data
to success
.
Lastly, add blogContainer
, blogTitle
, and blogBody
for styling the posts.
Open localhost:3000/post/1 to see your first blog post.
Create Posts Cell
Create a PostsCell
function and import the following above it:
Link
for linking to each blog post’s pageblogHeader
andlink
for styling the list output from the CellDefaultQueryCell
for creating the celltrpc
for executing the query
Create a type called BlogPostProps
with an id
and title
of type string
. Delete the Posts
component in src/pages/index.tsx
and move the useQuery
hook into the PostsCell
component.
Return DefaultQueryCell
with the query
set to postsQuery
. success
will map over the data
object and display a link for each blog post.
Import PostsCell
in src/pages/index.tsx
and return the component in the Home
function.
Deployment
Commit your current changes and create a new repository on GitHub with the GitHub CLI.
Deploy to Vercel
Install the vercel
CLI on your machine or add it to your project with pnpm
.
Use the following command to pass your database environment variable and deploy to Vercel. Use --confirm
to give the default answer for each question.
After the first deployment this command will deploy to a preview branch. You will need to include
--prod
to push changes directly to the live site for future deployments.
Open ajcwebdev-t3.vercel.app
to see your blog.
API endpoints are exposed on api/trpc/
, so ajcwebdev-t3.vercel.app/api/trpc/post.all
will display all blog posts.
Or you can hit the endpoint with curl:
For single blog posts try any of the following:
%7B%220%22%3A%7B%22json%22%3A%7B%22id%22%3A%221%22%7D%7D%7D
%7B%220%22%3A%7B%22json%22%3A%7B%22id%22%3A%222%22%7D%7D%7D
%7B%220%22%3A%7B%22json%22%3A%7B%22id%22%3A%223%22%7D%7D%7D
And copy them to the end of:
https://ajcwebdev-t3.vercel.app/api/trpc/post.byId?batch=1&input=
Check PageSpeed Insights for Desktop.
If what I know about these metrics is correct, then I believe 100 is considered a preferable score when compared to other scores which are not 100. PageSpeed Insights also gives a score for Mobile.
100 again! Equally as preferable!!
Deploy to Fly
Since create-t3-app
is mostly Next.js and Prisma at the end of the day, it can be deployed very easily on platforms like Vercel. But, in return for that ease of use, you will be taking a performance hit whenever your database is queried.
When Prisma is running in a Lambda function it has a noticeable cold start. Future guides in the ct3a documentation will demonstrate how to use platforms like Fly, Railway, and Render to deploy your project to a long running server. Install the flyctl
CLI and run the following command to initialize your project.
flyctl platform regions
to see available regions.
Resources, Articles, and Videos
Date | Title |
---|---|
2022-08-10 | Build a full stack app with create-t3-app |
2022-07-10 | ct3a End to End Tutorial Proposal |
2022-06-26 | T3 stack and my most popular open source project ever |
2022-05-21 | Build end to end typesafe APIs with tRPC |
Date | Title |
---|---|
2022-07-17 | Build a Live Chat Application with the T3 Stack |
2022-07-12 | The T3 Stack - How We Built It |
2022-07-10 | An Overview of the create T3 App |
2022-07-03 | The BEST Stack For Your Next Project |
2022-06-28 | Build a Blog With the T3 Stack |