A fullstack template for a NextJs App
A fullstack template for a NextJs App
All code from this tutorial as a complete package is available in this repository.
If you find this tutorial helpful, please share it with your friends and colleagues! For more like it you can subscribe on Youtube or follow me on Twitter.
This tutorial is available as a video lesson if you prefer that format:
{% youtube Iu5aZDqZt8E %}
"Next.js gives you the best developer experience with all the features you need for production: hybrid static & server rendering, TypeScript support, smart bundling, route pre-fetching, and more. No config needed."
As described in their words above, Next.js is very much an all-in-one fullstack modern application building solution. It includes first class support for Typescript and React, while offering easy solutions for some of the most common requirements in a modern application like routing, API, postCSS tools, and code-splitting.
It also supports both static site generation (for lightning fast static HTML pages that can be hosted anywhere) or with managed hosting services like Vercel/AWS/etc that run a Node server and support full on-demand data loading and server-side rendered pages.
Next.js has quickly become one of the most in demand skills in the web development space. This tutorial aims to act as kind of a "practical" extension to the documentation and help you set up a project using a lot of best practices that will improve your chances of keeping everything management as you scale.
This tutorial is not meant to replace the official documentation, which is absolutely fantastic. I highly recommend you take a read through at least the basic features section before you begin this tutorial, so you'll be familiar with the terminology and tools and some of the components they provide that are similar, but usually "more powerful" versions of their vanilla HTML counterparts.
Please review the table of contents to get an idea of each of the topics we will be touching in this extensive tutorial. I will freely acknowledge many of them are strict and opinionated configurations, if any of tem don't appeal to you then in most cases you can simply skip over those sections and should still be able to complete the tutorial without too much trouble.
Now, with all that said, if you are ready, let's dive right in!
We'll begin by creating a default Next.js application with a Typescript template.
npx create-next-app --ts nextjs-fullstack-app-template
cd nextjs-fullstack-app-templateFirst we will test to make sure the app is working. We're going to be using yarn for this example, but you could just as easily use NPM if you choose.
yarn install
yarn devYou should see the demo app available on http://localhost:3000
Also recommended to run
yarn buildTo ensure you can successfully do a production build of the project. It's recommended (but not required) to close your dev server when running a Next.js build. Most of the time there is no issue but occasionally the build can put your dev server in a weird state that requires a restart.
You should get a nice little report on the command line of all the pages built with green coloured text implying they are small and efficient. We'll try to keep them that way as we develop the project.
We would like for all developers working on this project to use the same Node engine and package manager we are using. To do that we create two new files:
.nvmrc - Will tell other users of the project which version of Node is used.npmrc - Will tell other users of the project which package manager is usedWe are using Node v14 Fermium and yarn for this project so we set those values like so:
.nvmrc
lts/fermium.npmrc
engine-strict=trueThe reason we are using v14 instead of v16 for Node is that later in the tutorial we will be deploying on Vercel which unfortunately still does not support Node 16. Perhaps by the time you read this tutorial it might. You can follow the progress here.
You can check your version of Node with node --version and make sure you are setting the correct one. A list of Node version codenames can be found here
Note that the use of engine-strict didn't specifically say anything about yarn, we do that in package.json:
package.json
"name": "nextjs-fullstack-app-template",
"author": "YOUR_NAME",
"description": "A tutorial and template for creating a production-ready fullstack Next.js application",
"version": "0.1.0",
"private": true,
"license" : "MIT"
"homepage": "YOUR_GIT_REPO_URL"
"engines": {
"node": ">=14.0.0",
"yarn": ">=1.22.0",
"npm": "please-use-yarn"
},
...The engines field is where you specify the specific versions of the tools you are using. You can also fill in your personal details if you choose.
This would be a good time to make our first commit to our remote repo, to make sure our changes are backed up, and to follow best practices for keeping related changes grouped within a single commit before moving to something new.
By default your Next.js project will already have a repo initialized. You can check what branch you are on with git status. It should say something like:
On branch main
Changes not staged for commit:
(use "git add ..." to update what will be committed)
(use "git restore ..." to discard changes in working directory)
modified: README.md
Untracked files:
(use "git add ..." to include in what will be committed)
.npmrc
.nvmrcThis tells us we are on the main branch and we have not staged or made any commits yet.
Let's commit our changes so far.
git add .
git commit -m 'project initialization'The first command will add and stage all files in your project directory that aren't ignored in .gitignore. The second will make a commit of the state of your current project with the message we wrote after the -m flag.
Hop over to your preferred git hosting provider (Github for example) and create a new repository to host this project. Make sure the default branch is se tto the same name as the branch on your local machine to avoid any confusion.
On Github you can change your global default branch name to whatever you like by going to:
Settings -> Repositories -> Repository default branchNow you are ready to add the remote origin of your repository and push. Github will give you the exact instructions when you create it. Your syntax may be a little different than mine depending on if you are using HTTPS rather than SSH.
git remote add origin [email protected]:{YOUR_GITHUB_USERNAME}/{YOUR_REPOSITORY_NAME}.git
git push -u origin {YOUR_BRANCH_NAME}Note that from this point on we will be using the Conventional Commits standard and specifically the Angular convention described here
The reason being like many other features in this project to simply set a consistent standard for all developers to use to minimize train-up time when contributing to the project. I personally have very little concern as to what standard is chosen, as long as everyone agrees to follow it that is the most important thing.
Consistency is everything!
In order to set a standard that will be used by all contributors to the project to keep the code style consistent and basic best practices followed we will be implementing two tools:
We'll begin with ESLint, which is easy because it automatically comes installed and pre-configured with Next.js projects.
We are just going to add a little bit of extra configuration and make it a bit stricter than it is by default. If you disagree with any of the rules it sets, no need to worry, it's very easy to disable any of them manually. We configure everything in .eslintrc.json which should already exist in your root directory:
.eslintrc.json
{
"extends": ["next", "next/core-web-vitals", "eslint:recommended"],
"globals": {
"React": "readonly"
},
"rules": {
"no-unused-vars": [1, { "args": "after-used", "argsIgnorePattern": "^_" }]
}
}In the above small code example we have added a few additional defaults, we have said that React will always be defined even if we don't specifically import it, and I have added a personal custom rule that I like which allows you to prefix variables with an underscore _ if you have declared them but not used them in the code.
I find that scenario comes up often when you are working on a feature and want to prepare variables for use later, but have not yet reached the point of implementing them.
You can test out your config by running:
yarn lintYou should get a message like:
✔ No ESLint warnings or errors
Done in 1.47s.If you get any errors then ESLint is quite good at explaining clearly what they are. If you encounter a rule you don't like you can disable it in "rules" by simply setting it to 1 (warning) or 0 (ignore) like so:
"rules": {
"no-unused-vars": 0, // As example: Will never bug you about unused variables again
}Let's make a commit at this point with the message build: configure eslint
Prettier will take care of automatically formatting our files for us. Let's add it to the project now.
It's only needed during development, so I'll add it as a devDependency with -D
yarn add -D prettierI also recommend you get the Prettier VS Code extension so that VS Code can handle the formatting of the files for you and you don't need to rely on the command line tool. Having it installed and configured in your project means that VSCode will use your project's settings, so it's still necessary to add it here.
We'll create two files in the root:
.prettierrc
{
"trailingComma": "es5",
"tabWidth": 2,
"semi": true,
"singleQuote": true
}Those values are entirely at your discretion as to what is best for your team and project.
.prettierignore
.yarn
.next
dist
node_modulesIn that file I've placed a list of directories that I don't want Prettier to waste any resources working on. You can also use patterns like *.html to ignore groups of types of files if you choose.
Now we add a new script to package.json so we can run Prettier:
package.json
...
"scripts: {
...
"prettier": "prettierNo open issues yet, or sync has not completed.