iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🏅

Trying out the Vercel Starter Kit for Quick Web App Development (React/Next.js/TailwindCSS/Prisma)

に公開

I am Masaki Suzuki from VTeacher.
All points are summarized in 3 lines or less where possible.
(Written in accordance with An Introduction to ReactJS Explained as Briefly as Possible)

What is the Vercel Starter Kit?

It was announced by Vercel this January.
It is a boilerplate for quickly building web applications that require login.
It supports multi-tenancy, making it easy to associate multiple domains with a single service.

https://demo.vercel.pub/platforms-starter-kit

  • Vercel for deployment (A hosting service that also includes basic CI/CD functionality)
  • Next.js as the React framework (A React framework made by Vercel)
  • NextAuth.js for authentication (Easy-to-use authentication for Next.js, made by Vercel)
  • Tailwind for CSS styling (A utility-first CSS framework)
  • Prisma as the ORM for database access (A TypeScript-friendly ORM; Rails fans will love it 👍)
  • PlanetScale as the database (A MySQL-based DB that allows branching like git)
  • TypeScript (This has become TypeScript-friendly since #PR15 was merged)
Preparation

Getting it running on Mac

Vercel has published a guide, so we will use it as a reference.

https://vercel.com/guides/nextjs-multi-tenant-application

That said, the above is a basic tutorial, so I will explain it with supplemental information below.
(Parts related to paid plans are excluded)

Steps

If you only want to try it out locally, the steps enclosed in dotted lines are unnecessary. Configuring the environment variables is a bit tedious (setting up PlanetScale, setting up GitHub apps for OAuth, etc.).

Prerequisites

  • Node version ">=12.22.0". Got "12.19.1"
  • An environment where you can use GitHub

0. Deciding on a Name

It is easier to decide on a name first. If you have an account, enter it.

This Codepen app (hoji) automatically generates URLs and commands that are tedious to type out. It is built with React + TypeScript + TailwindCSS. It saves to localStorage, so you can call it from anywhere as long as you use the same browser (please feel free to fork and modify it).

You can enter information in the green area.

From now on, you can refer to the information you entered from "Check your own information."

1. Create a GitHub Repository

To link with Vercel later, create a Git repository in advance (this is not necessary if you only want to try it locally).

GitHub: https://github.com/new

Check your own information

*The repository name will be the project name.
*When creating the repository, README.md is not required.

After creating the repository, clone it locally.

git clone git@github.com:{YourGitHubAccountName}/{RepositoryName}.git
Check your own information

Navigate to the project directory.

2. Start Development on Mac

Run create-next-app (a command to generate a project template, similar to Create React App) with the following options:

npx create-next-app --example https://github.com/vercel/platforms/tree/main .
  • The URL for --example is the Vercel Starter Kit repository.
    https://github.com/vercel/platforms/tree/main
  • The supported Node version is >=12.22.0. If you get error next@12.1.0: The engine "node" is incompatible with this module. Expected version ">=12.22.0". Got "12.19.1", please check your version.
    • Example: Use nodeenv to set the supported version
      $ echo "16.13.0" > .node-version
      $ cat .node-version
      16.13.0
      

Install Required Modules

Install the necessary modules.

npm install

3. Configure Environment Variables for Local Development ( .env )

Copy the provided env.example file.

cp .env.example .env

Let's take a look at the contents.

.env
### DEVELOPMENT ONLY VARIABLES

# Mandatory next-auth URL for localhost
NEXTAUTH_URL=http://app.localhost:3000
 
### PRODUCTION & DEVELOPMENT VARIABLES
 
# MySQL database URL for Prisma
DATABASE_URL=mysql://root@127.0.0.1:3309/platforms
 
# Github OAuth https://docs.github.com/en/developers/apps/building-oauth-apps/creating-an-oauth-apps
GITHUB_ID=
GITHUB_SECRET=
 
# Twitter Auth Bearer token (for static tweets)
TWITTER_AUTH_TOKEN=
 
# Secret key (generate one here: https://generate-secret.vercel.app/32)
SECRET=
 
AUTH_BEARER_TOKEN=
VERCEL_PROJECT_ID=
VERCEL_TEAM_ID=

Enter each environment variable into .env referring to the table below (don't forget to save your changes).

Environment Variable Required Notes
NEXTAUTH_URL Yes Default is fine
DATABASE_URL Yes Default is fine, but database setup is required (See explanation below)
GITHUB_ID Yes (See explanation below)
GITHUB_SECRET Yes (See explanation below)
TWITTER_AUTH_TOKEN Leave blank
SECRET Yes Secret key setting. Open the URL in .env Secret key in your browser, and paste the key displayed. Example: https://generate-secret.vercel.app/32
AUTH_BEARER_TOKEN Leave blank
VERCEL_PROJECT_ID Leave blank
VERCEL_TEAM_ID Leave blank

*Note: The following can be left blank, but if you want to set them (Team requires a Pro plan; 14-day free trial available):

Check your own information

DATABASE_URL

DATABASE_URL can remain as default (mysql://root@127.0.0.1:3309/platforms), but database configuration is required. The Vercel Starter Kit uses PlanetScale, which is MySQL-based.

If you don't have a PlanetScale account

Please create a PlanetScale account.
https://planetscale.com/

If you haven't installed the PlanetScale CLI

Please install the PlanetScale CLI.
https://docs.planetscale.com/concepts/planetscale-environment-setup

# For Mac.
brew install planetscale/tap/pscale
brew install mysql-client
  • Set it up with the DB name to be used (recommended: platforms).
    (The name can be changed. If you change it, please adjust accordingly.)

    pscale db create {DBName}
    
    Check your own information
  • Connect to the database in the cloud via the pscale command

    pscale connect {DBName} main --port 3309
    
    Check your own information

    *Do not close this terminal while using the database (to stop the database, use ctrl-c).
    *If you need to use a terminal, please open a separate tab.

  • Open a separate terminal tab and perform the migration:

    npx prisma db push
    
  • Promote the main branch from development mode to production mode:

    pscale branch promote {DBName} main
    
    Check your own information

GITHUB_ID / GITHUB_SECRET

This is for NextAuth configuration. You will be able to sign in with your GitHub account.

While signed in to GitHub, open the settings page below, click "New OAuth App", fill in the required fields, and register.
https://github.com/settings/developers

  • Enter http://app.localhost:3000/ for the Authorization callback URL.
  • Use the Client ID value for GITHUB_ID.
  • Use the Client secrets value for GITHUB_SECRET.
    (You can generate one by clicking the "Generate a new client secret" button)

GITHUB_ID

4. Run Locally on Mac

Once you have edited .env (don't forget to save!), let's check it in the browser. Open another terminal, run npm run dev, and then go to:

http://app.localhost:3000

Did it work? Congratulations! This is your first Vercel Starter Kit app. Try signing in with your GitHub account.
(Feel free to experiment locally later.)

5. Deploy to the Web

Please make sure you are linked (signed in) with your GitHub account on Vercel.

If you don't have a Vercel account

If you haven't registered yet, please create an account (linking with your GitHub account makes the process smooth).
https://vercel.com/

Import your GitHub repository.

How to Import a GitHub Repository

In this guide, we created a GitHub repository first. Let's start by committing and pushing your local files.

Search for the corresponding repository using the link below (in this example, search for {YourRepositoryName}), follow the instructions to set up access permissions, and then import it.

https://vercel.com/new

  • Next, register the Environment Variables. This is the Vercel equivalent of .env.
    *Note: The .env file is excluded from commits (it is listed in .gitignore)

Register the Environment Variables before deploying.

If you forgot to register Environment Variables

vsk

  • Environment variable names and values to register:
Environment Variable Name Value
NEXTAUTH_URL (Not required for production, so no need to register)
GITHUB_ID Register the info from .env for now (change later)
GITHUB_SECRET Register the info from .env for now (change later)
SECRET Register the info from .env and use it as is
DATABASE_URL Go to the link below, click Connect -> Connect with Prisma -> New Password. Use the generated DATABASE_URL (copy the string starting with mysql:// enclosed in '...'. Be careful that the password is not shown as asterisks)

*During local development, you connected to the cloud DB via the pscale command, but since you are deploying to Vercel, you need to use the official DATABASE_URL.

Deploy

Once you have registered the Environment Variables, click the Deploy button. If successful, you will see "Congratulations!". The preview will be a 404 at the moment, but click [Go to Dashboard] and make a note of the automatically assigned Vercel domain (DOMAINS).

(Example) vercel-starter-kit.vercel.app

Confirm your information
If the deployment fails
Reconfigure Environment Variables

Change the GITHUB_ID / GITHUB_SECRET you registered earlier. Create another GitHub app for the production environment (because the Callback URL changes), and register the Environment Variables. The steps are the same as before.

How to create a GitHub app (recap)

https://github.com/settings/developers

  • Click New OAuth App
    • Application name:
      vercel-starter-kit-product (anything is fine)
    • Authorization callback URL:
      https://{AssignedVercelDomainName}/api/auth/callback/github
      Confirm your information
How to reconfigure Environment Variables (GITHUB_ID/GITHUB_SECRET)
Modifying Code

Modify pages/_middleware.ts.
Middleware is a new feature in Next.js 12 that allows you to execute scripts before processing each request.

About Middleware (Introduced in Next.js 12)
pages/_middleware.ts (around line 33)
  const currentHost =
    process.env.NODE_ENV === "production" && process.env.VERCEL === "1"
      ? // You have to replace ".vercel.pub" with your own domain if you deploy this example under your domain.
        // You can use wildcard subdomains on .vercel.app links that are associated with your Vercel team slug
        // in this case, our team slug is "platformize", thus *.platformize.vercel.app works
        hostname
          .replace(appWildcardDomain, "") // Add this
          .replace(`.vercel.pub`, "")
          .replace(`.platformize.vercel.app`, "")
      : hostname.replace(`.localhost:3000`, "");
pages/_middleware.ts (around line 44)
  if (!pathname.includes(".") && !pathname.startsWith("/api")) {
    //if (currentHost == "app") { Change this as follows
    if (currentHost == "app" || currentHost == appHost /* Add this */) {

Finally, commit and push. Since you have already deployed to Vercel, Vercel will automatically run tests and redeploy once you push to master. Convenient, right? This mechanism is called CI/CD (Continuous Integration & Continuous Delivery).

Confirm your information
If you cannot sign in

Clear the cookies, local storage, and session storage for that page. If using Chrome, you can do this by right-clicking, selecting Inspect, and going to the Application tab.

Conclusion

How was it? Do you still have energy left?

"I want to do more. For example, custom domain settings or workflows."

See Part 2 (Practical Edition) here
https://zenn.dev/rgbkids/books/5c78aa8e2f14c1

Table of Contents

  • Using a custom domain
  • Workflow examples
  • How to create branches
  • Domain registration (Preview)
  • Environment variable registration (Production, Preview)
  • Adding columns to tables
  • Starter Kit supports Prisma as standard
  • Deploy Request
"I'm full."

Great work.

From here on, I recommend playing around with Next.js/React/TailwindCSS/TypeScript/Prisma locally.

For example, the following article is recommended!

Discussion