Max Next – Section 12 – Deploying NextJS Apps


Courses

Updated Jul 15th, 2021

Table of Contents

Chapter Details

Chapter 202. Module Introduction

Explore deployment options, steps to take before deploying, and actually deploy.

Chapter 203. Building NextJS Apps: Your Options

The two ways to deploy are the standard build and full static build.

The standard build is created via the “next build” command via the “run build” script. It produces optimized production bundles and a server-side app: requires NodeJS server. Cannot take output and put on static host (which you could do we standard/vanilla react app) because of the extra NextJS magic.

Pages are still pre-rendered (if possible) during the build process but a NodeJS server is required for API routes, server-side pages, and page revalidations. Also need a NodeJs server if using “getStaticPaths” with fallback set to true or blocking. With the standard build a re-deploy is needed if code changes or you don’t use revalidations and need page updates.

The full static build is created via the “next export” command. You can add this to the “package.json” file by creating a new “export” script (or you can add with double ampersands onto the existing “next build” command.) This command produces a 100% static app (HTML, CSS, JS) and does not need a NodeJS server.

With the full static build, certain NextJS features cannot be used: API routes, server-side pages, or page revalidations. Re-deployment is needed for all code and content changes.

Chapter 204. Key Deployment Steps

Add page metadata, optimize code (remove console.log statements, shrink as much as possible), remove unnecessary dependencies.

Use environment variables for variable data (ex: database credentials, API keys, etc.) For example in our blog project we have an API where we connect to the database and the connection string is hardcoded and it is more realistic to use a development database and production database and we need to swap the connection string depending on the environment. Api keys are enogh example of something to be managed with environment variables.

Do a test build and test the production-ready app on your local machine or on some test server.

After these three steps are complete it is time to deploy!

Chapter 205. Checking & Optimizing Our Code

Starting with step one described above, make sure all images are using “next/image.” NextJS also lazy-loads your page routes which is a very nice built-in feature.

Chapter 206. The NextJS Config File & Working With Environment Variables

NextJS has built-in support for environment variables.

Configure NextJS is possible, up to this point we have ben using the sensible defaults but maybe you want to fine-tune. Add a special “next.config.js” file to your root file which exports a JS object with NodeJS export syntax which is the equivalent to export default. Google for “next/config” to see what your options are. Environment variables, base path, rewrites, redirects. Inject your own webpack configuration is another example. You can disable compression if you don’t want to use it.

module.exports = {
  env: {
    customKey: 'my-value',
    mongodb_username: 'x',
    mongodb_password: 'y',
    mongodb_clustername: 'z',
    mongodv_database: 'w',
  }
}

// use with process.env.customKey

Note: Can use backticks to set a dynamic parts of mongoDB connection string for different values for development and production. Pretty good idea.

Certain hosts (like heroku, netflify and vercel) allow you set env variables in the hosting admin but for those hosts that do not leverage “phase” to define different config values based on dev or production

const {PHASE_DEVELOPMENT_SERVER} = require('next/constants')

module.exports = () => {
  if (phase === PHASE_DEVELOPMENT_SERVER) {
    return {
     env: {
      customKey: 'my-development-value',

      }
    }
  }  
  
  return {
   env: {
    customKey: 'my-non-development-value',

   }
  }
}

These also includes things like PHASE_EXPORT, PHASE_PRODUCTION_BUILD, PHASE_PRODUCTION_SERVER

Chapter 207. Running a Test Build & Reducing Code Size

Run “npm run build” command and we can see output in the console. See a red post-detail page size (320kb) which denotes you may be shipping too much code to the client, (these values are pre-compression). If you look at this component there is not a lot of code in this file especially when you consider we can disregard what is in “getServerSideProps” or “getStaticProps.” This is because of a 3rd-party package. In this case he needed to switch out SyntaxHighlighter for {light as SyntaxHighlighter} and make some minor changes from the code. Building again after making changes shows major reduction.

Chapter 208. A Full Deployment Example (To Vercel)

Running “npm run start” will run the production-ready application on localhost:3000 and will be super fast. Deploy this to any hosting provider that supports NodeJS server by uploading project code, run “npm install,” and then “npm start.” And then make sure internally you forward port 3000 to port 80 to the outside world, (These exact steps for this will depend on the hosting provider).

Vercel is highly optimized for NextJS. Netlify is also good. These also handle scaling very well.

Push project to remote repo (GitHub or similar) and tell Vercel to update any time this changes. Run “git init,” if you haven’t already done so, and make a commit. On github.com create new private repo and grab the link ending in .git

git remote add origin https://github.com/whatEvs.git
git push origin main

May need to set up personal access tokens if needed and use @ symbol and the token pre-fixed to the link above. This process is taking over for the deprecated way of adding email and password into terminal.

In Vercel give them access to your github repo and import. Can set environmental variables in Vercel if you don’t have in “next.config file.” Automatically uses CDN for speed and caching and will put our API routes into server-less functions. Lots of options and settings to dive into, (custom domains, etc.).

Note: May need to double check your mongo database has whitelisted IP.

Make any changes to your live site by “git pushing to main” which will then trigger a re-deployment.

Chapter 209. A Note On Github & Secret Credentials

Very important, “next.config.js” file needs to be in your repo so Vercel can see it. But it can also be read by anyone with access to your repository, (team members on private repo or public or repo). May want to just set the environment variables options on host’s admin website instead of in code.

Chapter 210. Using the “export” Feature

No server-side code; no page revalidations, no fallback, no “getServerSideProps,” no image optimization (Link form ‘next/link’), you can create a “next export” script that runs “next export” which will build an “out” folder with your project which then you can deploy to a static host.

Chapter 211. Module Summary

Chapter 212. Module Resources