Temporal
Course Description
Find the end-to-end type-safety strategy that works with your stack! Share TypeScript types between client and server applications. Take the guesswork out of API changes with Zod schemas, and every response is what you expect. Write tRPC on both the client and server for a smoother developer experience. Simplify database migrations with Prisma and generate your Zod schemas for air-tight type contracts between the database, server, and client.
This course and others like it are available as part of our Frontend Masters video subscription.
Preview
CloseLearn Straight from the Experts Who Shape the Modern Web
Your Path to Senior Developer and Beyond
- 200+ In-depth courses
- 18 Learning Paths
- Industry Leading Experts
- Live Interactive Workshops
Table of Contents
Introduction
Section Duration: 9 minutes
- Steve Kinney begins the course by sharing some of the challenges of end-to-end type safety. While both the frontend and backend applications might have strong type safety, a lot of trust is implied with the data sent between the two ends of the stack. This course will explore techniques for solving type safety issues across the full stack.
Zod Schema Validation
Section Duration: 1 hour, 9 minutes
- Steve compares type guards with schema validation libraries. Type guards often require extra conditions to ensure a value has the correct shape and is the expected type. Scheme validation libraries provide a more readable and concise API for this same validation.
- Steve introduces Zod, a schema validation library explicitly built for TypeScript, and briefly walks through the documentation. Some basic validation examples are shared along with the performance benefits.
- Students are instructed to solve several schema validation challenges. The solution to the first four challenges can be found in this lesson.
- Steve continues demonstrating the solution to the Zod Basics exercise. The solution to challenges 5 through 10 can be found in this lesson.
- Students are instructed to solve more advanced Zod schema validation challenges involving lazy recursion and preprocessing.
- Steve discusses the challenges of using JSON schemas. One technique includes creating a Zod schema and converting it to JSON. This lesson also includes a demonstration using the satisfies keyword to ensure a schema matches an existing type.
API Type Safety
Section Duration: 1 hour, 13 minutes
- Steve spends a few minutes walking through the Todo app and API. The project has directories for both the client and server applications. Each application needs to be started either with the VS Code "Start" task or by opening two terminals and running "npm run dev" in each directory.
- Steve adds Request and Response types to one of the Express route handlers. This satisfies TypeScript, however, these types do not prevent errors when unexpected data is sent to the API. A better system for checking data at runtime and handling errors is needed.
- Steve creates a schema validation for the request body sent to the Express server. Partial schemas are also created for routes where the id property needs to be omitted. This lesson also includes a demonstration of inline Zod schema validation.
- Steve copies the TaskSchema from the server to the client project and demonstrates how to apply the validation to the fetch request. A more practical approach covered in the next lesson is sharing the schemas between both the client and the server.
- Steve refactors the client and server projects by moving the schemas into a shared package. This allows them to be imported into each project, and there is one source of truth for schema validation.
- Students are instructed to add type safety through schema validation to an Express API server project with Zod.
- Steve adds schema validation to the request body in an Express middleware. When the middleware is used in another route, the typing information is passed to the route handler. This alleviates the need to add schema validation to every handler and use the middleware for validation instead.
- Steve creates a validateBody middleware that is abstracted to accept any Zod schema and validate the incoming request's body. This can be reused through the Express application and reduce boilerplate validation logic for each request.
- Students are instructed to create validators for the Express query and path parameters. The validateBody method can be used as an example for each validator.
API Contracts
Section Duration: 25 minutes
- Steve introduces the OpenAPI specification, which is a formal standard for describing HTTP APIs. Since it's language agnostic, API contracts can be created and shared between different client and server languages.
- Steve generates TypeScript types from an OpenAPI contract. The types are then imported into the API client app. This not only adds end-to-end type-checking but also validates API route URLs.
- Steve introduces the openapi-express-validator package that automatically validates API requests and responses. The validator is installed as an Express middleware, allowing it to intercept any requests and responses requiring validation.
tRPC
Section Duration: 49 minutes
- Steve introduces tRPC, which allows developers to easily build & consume fully typesafe APIs without schemas or code generation. Full-stack projects using TypeScript can share types directly between client and server applications. Developers enjoy the ergonomics because the API endpoints resemble function calls.
- Steve scaffolds the tRPC support for the server application. An adapter is created to initialize the router and add it as an Express middleware. A context module initializes the tRPC client and the tRPC procedures.
- Steve codes the initial tRPC query for retrieving tasks. The procedure initially includes the database queries. Later, the database queries are refactored into a TaskClient module that can be reused more easily.
- Steve jumps to the completed code example for the TaskClient. tRPC mutations are added to the taskRouter to handle updating and deleting tasks. The tRPC server integration is completed by adding the `/api` endpoint to the Express application.
- Steve refactors the client application to use the tRPC server endpoint. The code for the CRUD implementation is drastically reduced since the boilerplate fetch API is no longer required. Each API call reads like a function call and is type-safe.
Type-Safe Databases
Section Duration: 19 minutes
- Steve introduces Prisma, which provides a TypeScript ORM and a declarative database migration system. Once a Prisma schema is created, database migration files are generated containing the new objects.
- Steve refactors the tRPC taskRouter to use Prisma. When the PrismaClient is initialized, database APIs for any custom objects are available and type-safe. These APIs include methods like create, delete, findOne, findMany, etc.
- Steve demonstrates how to generate Zod schemas and tRPC methods from Prisma. OpenAPI is also revisited and Swagger is added to the project to provide feature-rich API documentation site for the application.
Wrapping Up
Section Duration: 2 minutes
- Steve wraps up the course by summarizing the pros and cons of full-stack type-safety across an application. While there isn't a one-size-fits-all approach to type safety, the abundance of tooling gives teams flexibility based on their stack, application environment, or unique constraints.
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops