The evolution of NextJS and Type safety

The evolution of NextJS and Type safety
Photo by Sigmund / Unsplash
💡
The code in this article is available on my repo

Background

For those unfamiliar with the term, T3 Stack refers to the combination of five powerful technologies: NextJS, TailwindCSS, Prisma, tRPC, and NextAuth. Together, these tools allow for creation of blazingly-fast, secure, and visually stunning full-stack applications. And it does it by putting type safety as a first class citizen.

But T3 Stack didn't just appear out of thin air. Each component has its rich history and evolution. In this article we'll go over a little history of the stack, why type safety matters, and run through getting started with T3. Let's go.

TypeScript and the Rise of Type Safety

As any seasoned developer knows, JavaScript has long been the go-to language for building web applications. However, its dynamically-typed nature can sometimes lead to headaches, especially when working on larger, more complex projects. This is where TypeScript comes in.

First introduced in 2012, TypeScript is a super-set of JavaScript that adds optional static typing to the language. In a TypeScript project, the developer can define variables with a specific data type (such as string, number, or boolean). The compiler will catch any type mismatches before the code is even run.

But TypeScript isn't just about catching bugs. It also offers improved code completion, refactoring, and class-based object-oriented programming. It's no wonder that TypeScript has gained widespread adoption in the development community, with many developers touting its improved readability and maintainability.

So how does this relate to NextJS? As a framework for building server-rendered React applications, NextJS gained popularity quickly. But with TypeScript support added in version 9.3, NextJS has earned a seat at the TypeScript table. Using TypeScript with NextJS allows for even more robust and scalable applications, making it a match made in heaven for developers looking for a powerful, typesafe solution.

Why T3 is a powerhouse

You could be excused for initially believing T3 is just another create-next-app but it's much more than that. As I mentioned in my 2022 Tech Wrap-up article, T3 is the avengers of Typescript and its power is more than the sum of its parts.

  • Prisma creates a typescript interface for your database objects
  • tRPC creates API endpoints/consumers
  • Zod brings along TypeScript-first validation you can use on the back and frontend
  • TailwindCSS took CSS utility methods to a whole other level. Allowing for the  creation of fully customized sites much faster
  • NextAuth makes authentication a snap. You have better things to do than worry about OAuth handshakes.

And if any of these T3 parts are not needed, you don't have to use them. During creation they are not included by default.

Getting Started

Ok let's get into it. To get started with T3, it's good to reference the installation docs. Use your favourite package manager but for me that'll be pnpm at the time of writing.

pnpm create t3-app@latest
Step 1 of T3 Stack create T3 app on the cli
💡 Tip: Not a trick question, TypeScript is the correct answer

As mentioned above, included packages are unselected by default to encourage minimalism. You can press a to toggle them all on or you can use the space bar and arrow keys to create your own combination.

Select the packages you need for your project

Move inside the directory with cd YOUR_PROJECT_NAME and then run the NextJS dev command to start it up locally. Navigate to http://localhost:3000 and you should see the app running!

Running the T3 app locally on localhost:3000

That's great. So now have a running NextJS app with several useful goodies. But you're typically not done yet. Here are a couple common things you should look at before starting to build your next big thing:

NextJS 13 Layouts in T3

T3 is now on NextJS 13 but it doesn't take advantage of all the new features out of the box. Particularly the layouts and server components which are in the app directory. While it is in beta, it does offer some very solid advantages and seems to be in a good place. But please do your due diligence and test it to ensure it works for your use-case.

To enable the app directory in T3, open next.config.mjs and add the following flag to config:

const config = {
  experimental: {
    appDir: true,
  },
  ...
next.config.mjs

Then create the new index page with a file src/app/page.tsx

// app/page.tsx
// This file maps to the index route (/)
export default function Page() {
  return <div className="text-5xl">Hello, Next.js!</div>
}
src/app/page.tsx

If you run it now you'll see an error message, you now have two files that map to the index / route.

Remove src/pages/index.tsx and the error should go away.

You may also notice NextJS created two more files: head.tsx and layout.tsx. To dive deeper into what these are as well as a better understanding of Layouts, I'd suggest reading the Layouts RFC as they go into many scenarios you may find useful.

For now let's edit the layout.tsx to look like this:

import Link from "next/link"
import "../styles/globals.css"

const btnClasses = "p-2 mx-1 text-blue-500 border border-blue-500 hover:bg-blue-600 hover:border-blue-700 hover:text-white rounded-md shadow-sm"

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html>
      <head />
      <body>
        <div className="p-5 border shadow-sm">
          <Link href="/" className={btnClasses}>Home</Link>
          <Link href="/blog" className={btnClasses}>Blog</Link>
        </div>
        <div className="p-5">{children}</div>
      </body>
    </html>
  )
}
src/app/layout.tsx

Importantly, we added the tailwind styles into our app. And we also added btnClasses which has some tailwind stylings that you'll probably want to move to a component when you're satisfied this demo works. Next, let's make a file at src/app/blog/page.tsx

// This file maps to the route (/blog)
export default function Page() {
  return <div className="text-5xl">Hello, Blog!</div>
}
src/app/blog/page.tsx

Now you should see a navbar which is created in the layout, and is reused between the subpage /blog. It should like something like this:

http://localhost:3000

Clicking on blog you'll go to the blog page

http://localhost:3000/blog

Also, try doing a next build. Now that you have your app directory working, you should see the pages with api routes and your app directory sizes there after a successful build

pnpm build

Summary

💡
The code is available on my repo

To wrap it up, T3 Stack is a powerful combination of technologies that allows developers to build faster, more secure, and visually stunning web applications. By combining NextJS with tools like TailwindCSS, Prisma, tRPC, and NextAuth, developers have a vast array of tools to create truly unique applications.

But the T3 Stack isn't just about the present. It's also about the future. As NextJS and TypeScript continue to evolve and improve, we can expect even more exciting developments in the world of T3 Stack. Whether you're just starting with web development or are a seasoned pro, the T3 Stack is worth a look.

I hope you enjoy it.