Part 1 – Full Stack Todos Application with NextJS, Prisma (using SQL Server), and Redux Toolkit (RTK)

The purpose of this document series is to describe the steps that are necessary to create a “Todos” application using NextJS, Prisma, and Redux Toolkit (RTK).

NextJS is an exciting development tool to create web applications because they allow your Server Code and Client Code to be in the same repository. It is essentially like having a NodeJS server application and REACT Application in the same repository.

TLDR, show me the code: https://github.com/woodman231/nextjs-prisma-todos-rest

TOPIC: Create a Development Container, Create the Next App and Install Required Dependencies

This first steps involves created a development environment that is independent of dependencies on your local computer. Instead the dependencies will be provided within the development container, so that developers that we share the code with will not need to make modifications to their computer to join us on our adventure.

Create the Development Container

To get started I will be creating a new directory on my computer called “nextjs-prisma-todos-rest”.

Open the directory in visual studio code.

Within Visual Studio Code do a CTRL+SHIFT+P to bring up the command pallet and select the options to “Dev Containers: Add Dev Container Configuration Files.”

Next, select the “C# (.NET) and MS SQL” option (I know we will be using NodeJs really, but this is a good template to start from since it has MS SQL preconfigured for us
Now use the default options to create your files.

Once complete, you should have a directory structure similar to this:

To the devcontainer.json file — change the name field to be “Nodejs and MS SQL”.

To the Dockerfile — update the first line of FROM to be…

FROM mcr.microsoft.com/devcontainers/javascript-node:0-18
Once your files have been saved. Open the Visual Studio Command Pallet (CTRL+SHIFT+P) and select the option for “Dev Containers: Rebuild and Reopen in Container.”
It will take a minute or more to create the dev container. You can click the show log if you like.

Once it is done your docker desktop should look something like this:

Confirm connectivity to MS SQL Server

Let’s confirm our connection to the SQL server before we go much further.

In VS Code click on the SQL Server button on the left.

Double click on the mssql-container button:
When prompted enter in the password from the devcontainer.json file. When prompted accept the server certificate. If it doesn’t work right away you may be prompted to retry, confirm that the server is “localhost,1433”, no default database, the username of “sa”, the password of “P@ssw0rd”, keep the default name of “mssql-container” and yes you do want to accept the server certificate.

Once connected we can see that there is already a Database with no table called “ApplicationDB”. For our demonstration we will use this database.

Create the NextJS App

Let’s start by creating our next app. Do a CTRL+SHIFT+` to bring up a terminal. These terminal commands will be issued in the devcontainer and not your local computer. Execute the following command:

npx create-next-app@latest
For purposes of this demonstration, I selected the following options:
When that is complete you should have a directory structure like this:
There is a weird problem with using nextjs in a development container where the Hot Module Reloading (HMR) doesn’t work properly out of the box. To fix that, edit the next.config.js file to have the following code.
/** @type {import('next').NextConfig} */
const nextConfig = {
    webpack: function (config, context) {
        config.watchOptions = {
            poll: 1000,
            aggregateTimeout: 300,
        };

        return config;
    }
}

module.exports = nextConfig

Install and Initialize Prisma

In the terminal execute the following commands:

npm install prisma --save-dev
npm install @prisma/client --save
npx prisma init
Doing this modified our package.json to save prisma as a development dependency and the prisma client to be a regular dependency. Furthermore, after initializing prisma we now have a .env file and a prisma directory with a schema.prisma file.
The default initialization assumes postgres. Since we are using sql server we need to set some things straight. Open the .env file and change the DATABASE_URL to the following:
DATABASE_URL="sqlserver://localhost:1433;database=ApplicationDB;user=sa;password=P@ssw0rd;encrypt=true;trustServerCertificate=true"
That username and password should look familiar to you based on the contents of the devcontainer.json file, and the exercise we went through to connect to the dev containers sql database.

Now is the time for us to create our Todos table.

Edit schema.prisma to have the following code:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "sqlserver"
  url      = env("DATABASE_URL")
}

model Todo {
  id Int @id @default(autoincrement())
  title String @db.VarChar(255)
  dueDate DateTime @db.DateTime
  done Boolean @default(false)
}
Notice that we also changed the provider in the datasource to “sqlserver” instead of “postgres”; however the URL we left as the same environment variable.

For more information about writing the schema file see: https://www.prisma.io/docs/concepts/components/prisma-schema

NOTE: I would like to point out that at this time prisma only officially supports one “schema.prisma” file. You can add as many table definitions as you like to this file. There is a third-party solution available on NPM called prismix at https://www.npmjs.com/package/prismix/v/1.0.19, as well as the associated GitHub repository @ https://github.com/jamiepine/prismix. (At the time of this writing this prismix github repository is in public archive mode. Which means it is no longer being maintained by the developer. There is a thread on GitHub requesting an official solution, but it doesn’t look like it has been fulfilled. You can check this link to see if has been updated: https://github.com/prisma/prisma/issues/2377.)

For the purposes of this demonstration we will stick to the single file, but I did think it was important to point out this limitation, and the risk with using the third part solution that is no longer maintained.

Once all of the files are saved it is now time to create our first migration. Execute the following code:

npx prisma migrate dev --name init
The CLI should output something like this:
If we refresh the SQL Server connection it should now look like this:
Do a right-click and “Select top 1000” on both the migrations and Todos tables to review the results
The field names have the same case of field names that we used in our prisma.schema file. If your organization has different field naming standards than what I demonstrated here, that is fine, you can adjust the code to fit that.

Install and Initialize Zod Schema Validation

Zod is a Typescript-first schema declaration and validation Library. While Prisma alone generates TypeScript types that we can use through out or application. It does not supply validation. We want to be sure that the REST Requests that we receive are valid for the data we are going to pass along to the database request.

Execute the following command:

npm install prisma-zod-generator
Modify the prisma/schema.prisma file to include the zod generator.

The file should now look like this:

// This is your Prisma schema file,
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
  provider = "prisma-client-js"
}

generator zod {
  provider = "prisma-zod-generator"
}

datasource db {
  provider = "sqlserver"
  url      = env("DATABASE_URL")
}

model Todo {
  id Int @id @default(autoincrement())
  title String @db.VarChar(255)
  dueDate DateTime @db.DateTime
  done Boolean @default(false)
}
Execute the following command:
npx prisma generate
We should now have the following files:
I will put a pin in that for now and we will use some of these files later.

Conclusion

Creating a development environment that includes the database that you will be using as well as the node version that you will be using will streamline the onboarding process for other developers as they come on to help with the project.

Parts:

Part 1 – Create a Development Container, Create the Next App and Install Required Dependencies
Part 2 – Configure the REST Server Features
Part 3 – Configure the REST Client Features

About Intertech

Intertech is a Software Development Consulting Firm that provides single and multiple turnkey software development teams, available on your schedule and configured to achieve success as defined by your requirements independently or in co-development with your team. Intertech teams combine proven full-stack, DevOps, Agile-experienced lead consultants with Delivery Management, User Experience, Software Development, and QA experts in Business Process Automation (BPA), Microservices, Client- and Server-Side Web Frameworks of multiple technologies, Custom Portal and Dashboard development, Cloud Integration and Migration (Azure and AWS), and so much more. Each Intertech employee leads with the soft skills necessary to explain complex concepts to stakeholders and team members alike and makes your business more efficient, your data more valuable, and your team better. In addition, Intertech is a trusted partner of more than 4000 satisfied customers and has a 99.70% “would recommend” rating.