Learn Next.js · 15/15

Deployment & Production Readiness

7 min read

Hello there, future Next.js pro! So, you've built a dazzling application. It works like a charm on your local machine. But now it's time for the grand finale: showing it to the world. This is where Deployment and Production Readiness comes in. Think of it as preparing your masterpiece for its first art gallery exhibition. You need to make sure the lighting is right, the frame is secure, and it’s ready for the critics (a.k.a your users). Let's get your app ready for its big debut! 🚀

1. Environment Variables: Managing .env for Local and Production 🤫

The Problem: Your application often needs secret keys, database URLs, or API tokens to work. Hardcoding these directly into your code is a terrible idea. It’s like leaving the keys to your house under the doormat. If you share your code on a public platform like GitHub, everyone can see your secrets. We definitely don't want that.

The Solution: Environment variables to the rescue! These are variables that live outside your codebase, and you can tell your application how to access them. Next.js has a built-in system for this using a special file called .env.local.

Imagine you're a secret agent. You have a confidential informant (your API) and a secret code (your API key) to communicate. You wouldn't write down the secret code on a public bulletin board (your code). Instead, you'd keep it in a secure, private location (.env.local) that only you (your local development environment) can access.

How it Works in Next.js:

Next.js makes this super simple. You create a file named .env.local in the root of your project.

bash
# .env.local

DB_HOST=localhost
DB_USER=myuser
DB_PASS=supersecretpassword

Accessing Environment Variables:

Now, how do you use these in your code? By default, any variable you define in .env.local is only available on the server-side (in your API routes or getServerSideProps). This is a security feature to prevent you from accidentally leaking your secrets to the client-side browser.

To access them, you use process.env:

javascript
// In a server-side file (e.g., an API route)

export default function handler(req, res) {
  const dbHost = process.env.DB_HOST;
  // ... connect to the database
  res.status(200).json({ name: 'Secret Data' });
}

What about the Browser?

Sometimes, you need to use an environment variable in your client-side code (your React components). For this, you need to prefix the variable name with NEXT_PUBLIC_.

bash
# .env.local

NEXT_PUBLIC_GOOGLE_ANALYTICS_ID=G-XXXXXXXXXX

Now, you can safely access this in your components:

javascript
// In a component file

function AnalyticsTracker() {
  const gaId = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_ID;
  // ... use the ID to initialize analytics
  return <div>Tracking your page views!</div>;
}

✨ Funny Exaggeration: If you forget to prefix with NEXT_PUBLIC_ for a browser variable, your app will act like it has amnesia when you ask for that variable on the client-side. It will simply pretend it doesn't exist!

Industry Standard:

  • Never commit .env.local to Git. Add .env.local to your .gitignore file.
  • For production, you'll set these variables in your hosting provider's dashboard (we'll see this with Vercel).
  • You can have different .env files for different environments like .env.development and .env.production. Next.js will automatically pick the right one.

2. Running the Production Build Locally (next build) 🏗️

The Problem: When you run next dev, you're in development mode. This mode is optimized for a great developer experience with features like hot-reloading. However, it's not optimized for performance. It's like a chef meticulously preparing a single dish for tasting. For a real restaurant service, you need to batch-prepare and optimize everything.

The Solution: You need to create a production-ready, optimized version of your application. This is what next build is for.

What next build Does Under the Hood:

When you run next build, Next.js performs a flurry of activities:

  • Compiles: It takes your React code and turns it into highly optimized JavaScript that browsers can understand efficiently.
  • Bundles: It groups your code into smaller chunks (bundles) so the browser only loads what's necessary for the current page.
  • Minifies: It removes all unnecessary characters from your code (like spaces and comments) to make the file sizes as small as possible.
  • Renders Static Pages: If you have pages using getStaticProps, it pre-renders them into static HTML files.

How to Do It:

  1. Build the application:

    bash
    npm run build
    # or
    yarn build

    This command reads your package.json and runs the next build script. You'll see a .next folder appear in your project. This is your production-ready app.

  2. Start the production server:

    bash
    npm run start
    # or
    yarn start

    This command starts a production server using the output from next build. This is how your app will run on a real server.

By running the production build locally, you can catch any issues that might only appear in the production environment. It's your final dress rehearsal before the big show!

3. Deploying Seamlessly to Vercel ☁️

The Problem: You have your production-ready build. Now what? You need a place to host it. Setting up a server from scratch can be a daunting task involving configuring servers, managing domains, and setting up SSL certificates.

The Solution: Vercel! Vercel is a platform created by the same team that created Next.js. Deploying a Next.js app to Vercel is so smooth, it feels like magic.

The Vercel Deployment Flow (It's this easy):

  1. Push your code to a Git provider: Make sure your project is on GitHub, GitLab, or Bitbucket.
  2. Sign up for a Vercel account: You can sign up with your Git provider account.
  3. Import your project: On your Vercel dashboard, click "Add New... -> Project".
  4. Select your Git repository.
  5. Configure the project (optional): Vercel is smart and will automatically detect that you have a Next.js project. The default settings are usually perfect. This is where you would also add your production environment variables that we talked about earlier!
  6. Click "Deploy".

That's it! Vercel will now:

  • Pull your code.
  • Run next build.
  • Deploy your application to their global network.
  • Give you a URL to your live site.

Continuous Deployment:

The best part? Every time you push a new commit to your main branch, Vercel will automatically redeploy your application with the latest changes. It's a hands-off, worry-free experience.

4. Next.js Analytics and Performance Monitoring 📊

The Problem: Your application is live! 🎉 But how do you know if it's performing well? Are users having a fast experience? Are there any errors? Flying blind is not a good strategy.

The Solution: Vercel Analytics provides a simple way to monitor your application's performance and gather insights about your audience, with a strong focus on privacy.

How to Enable Vercel Analytics:

  1. Go to your project's dashboard on Vercel.
  2. Click on the "Analytics" tab.
  3. Click "Enable".

Just like that, Vercel will start collecting data.

What You Can Monitor:

  • Real Experience Score: It measures your site's performance based on Core Web Vitals, which are metrics Google uses to measure user experience.
  • Pageviews & Visitors: See how many people are visiting your site and which pages are the most popular.
  • Data is privacy-friendly: It doesn't use cookies and is compliant with privacy regulations like GDPR.

Performance Monitoring:

For more in-depth performance monitoring and error tracking, developers often use third-party tools like:

  • Sentry: Excellent for catching and debugging errors in production.
  • LogRocket: Lets you replay user sessions to see exactly what they did and where they ran into issues.

Integrating these tools usually involves adding a small code snippet to your application.

By keeping an eye on your analytics and performance, you can ensure your users are always having a smooth and fast experience on your site. It's like having a health monitor for your application! 🩺

And there you have it! You've gone from a local project to a production-ready, globally deployed application with monitoring in place. You're no longer just a developer; you're a full-fledged Next.js deployer!


References for Extra Reading 📚

Challenge

You are building a settings page (SettingsPage) for a Next.js application using the App Router. Your task is to correctly access and display configuration values from environment variables.

  1. Within the SettingsPage server component, access a server-side only environment variable named DATABASE_URL.
  2. Create a variable dbStatus that holds a string indicating the connection status, like: "Connected using [the value of DATABASE_URL]".
  3. Access a second, client-side environment variable named NEXT_PUBLIC_ANALYTICS_ID.
  4. The component must render two paragraphs inside the main div:
    • The first paragraph should display the text: "Analytics ID: [the value of NEXT_PUBLIC_ANALYTICS_ID]".
    • The second paragraph should display the text: "Database Status: [the value of dbStatus]".

Expected result

The submitted code should be a single React component, SettingsPage, that correctly implements the following:

  • It accesses the server-side environment variable process.env.DATABASE_URL and stores a derived status message in a local variable.
  • It accesses the client-side environment variable process.env.NEXT_PUBLIC_ANALYTICS_ID.
  • The component's return statement includes two <p> tags within the <div>.
  • The first <p> tag displays the NEXT_PUBLIC_ANALYTICS_ID.
  • The second <p> tag displays the database status message derived from DATABASE_URL.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.