Perfsol logo
Contact
Scroll to top

Next.js: Expert Guide on Setting Up the Development Environment and Going Live With Your App

July 20, 2024

Mykola Breslavskyi

Author

Mykola Breslavskyi

CTO

page.tableOfContents

Introduction to Next.js

For anyone involved with web applications or seeking to develop one, Next.js must have crossed their radar. But what does this technology stand for? What benefits does it bring? How to install Next.js and more setup tips in this article.

About Next.js in a Nutshell

Next.js is one of the React frameworks that can be used for creating applications with server-side rendering (SSR) and static site generation (SSG) at the same time. This peculiarity has an immense positive impact on the performance; therefore, more and more CTOs and Lead Developers use it in their own and clients’ projects. If you know HTML, CSS, and React, coding in Next.js will be as easy as ABC.

What are Next.js Key Features and Benefits?

From a strategic point of view, Next.js is a great choice for building "universal" web apps. Such apps are also known as isomorphic apps. This means that such an app can share code between the client and server. With this approach, you get:

Scalable app. No matter where your business goes, you won't need to start from the very beginning. You can always scale your existing app or adapt its logic.

SEO-friendly app. If you’ve ever thought about the marketing future of your app, that’s a never-ignore thing to perform well in search engine rankings.

Faster load times. Features like ISR and automatic code splitting help reduce the initial load time and improve user experience. Say goodbye to long waiting times and user annoyance.

Simplified configuration. You can focus on building your application rather than setting it up.
API routes. You can build full-stack applications within the same framework using API routes. No need for different workarounds and tricks.

Incremental static regeneration (ISR). Your static content is updated after deployment without rebuilding the entire site.

File-based routing. Next.js has an easy-to-use file-based routing system without the need for additional libraries.

Rich ecosystem. Next.js has extensive documentation and a rich ecosystem of plugins and tools so your development team will be well-equipped to start with this framework.

Setting up pages. Next.js can handle both static and dynamic page routes. Static routes are like '/dashboard', '/about'. Dynamic pages are individual blog posts, products, or news articles. To handle this, you should add a folder called [slug] (or [post] or [item]) to your 'app' folder. Then, in the page.tsx file, you can use the generateStaticParams method, which should generate an array of all possible page names.

Setting Up the Development Environment

Before we start all the magic with a new Next.js project, let’s make sure you have Node.js, npm (Node Package Manager), and a code editor installed.

Installing Node.js

First, check if you have Node.js installed.

Windows:

  • Open Command Prompt or PowerShell.
  • Type node -v and press Enter.
  • If Node.js is installed, you will see the installed version number as a result. If not, you'll see an error message indicating that node is not recognized as a command.

macOS and Linux:

  • Open your terminal.
  • Type node -v and press Enter. This simple command checks if there’s Node.js on your system.
  • The version number will be shown to you if Node.js is installed. If not, you'll see an error message indicating that node is not found or isn't installed.

If not, simply follow these instructions:

1. Download Node.js:

  • Go to Node.js website.
  • Click on the "Download".
  • Choose the LTS (Long-Term Support) version.

Install on Windows:

  • Once downloaded, open the installer (.msi file).
  • Follow the installation wizard instructions.
  • Accept the agreement and click "Next" through all the prompts.
  • "Finish" to complete the installation.

Install on macOS:

  • Open the downloaded .pkg file.
  • Follow the installation instructions.
  • Accept the license agreement and click "Install".
  • Enter your password if prompted.
  • Click "Install Software" to complete the installation.

Install on Linux:

  • For Debian/Ubuntu:
sudo apt-get install nodejs
  • For Red Hat/Fedora:
sudo dnf install nodejs
  • Alternatively, download the binaries from the Node.js website and install manually.

2. Verify Installation:

  • Open Command Prompt or Terminal.
  • Type node -v and press Enter to check the installed Node.js version.
  • Type npm -v and press Enter to check the installed npm version.

Congrats, Node.js is now installed and ready to use!

Installing npm

Verify if you have npm installed at all.

For Windows, macOS and Linux:

  • Open Command Prompt, Terminal or PowerShell.
  • Type npm -v and press Enter.
  • Get the npm version or an error message.

To install npm, you typically have to get Node.js first, as npm comes bundled with Node.js. This step we have already completed. To install npm:

  • Open Command Prompt or Terminal.
  • Run npm install npm@latest -g. This command installs npm globally (-g flag) and makes sure you have the latest version.
  • Verify npm Installation. After installation completes, type npm -v and press Enter. If npm is installed correctly, it will display the installed version number.

Installing a Code Editor

Do you have a specific application for writing code locally? No? Let’s install Visual Studio Code. It's one of the most user-friendly code editors, and it’s also free. How to install Visual Studio Code:

1. Download:

Windows:

  • Once downloaded, open the installer.
  • Follow the installation wizard instructions.
  • Complete the installation by clicking "Finish".

macOS:

  • Open the downloaded .dmg file.
  • Drag Visual Studio Code into the Applications folder.
  • Launch Visual Studio Code from the Applications folder.

Linux:

  • For Debian/Ubuntu:
sudo apt-get install code
  • For Red Hat/Fedora:
sudo dnf install code
  • Alternatively, download the .deb or .rpm package from the website and install it manually.

2. Open Visual Studio Code.

You're ready to start writing code!

Creating a New Next.js Project

And the final step is to install Next.js and create your app.

  • Create a folder for your project wherever it’s convenient for you.
  • Open VS Code and navigate to the created folder.
  • In the VS Code terminal, run the command:
npx create-next-app@latest

This step will install Next.js and create your first app with a default structure. Now, let’s explore the configuration.

Next.js Project Configuration

What is your project named?

If you created the app directly from your machine terminal, not via an already created folder, you might be asked the name of your app.

Would you like to use TypeScript?

No / Yes

Would you like to use ESLint?

No / Yes

Would you like to use Tailwind CSS?

No / Yes

Would you like to use the src/ directory?

No / Yes

Would you like to use App Router? (recommended)

No / Yes

Would you like to customize the default import alias (@/*)?

No / Yes

What import alias would you like configured? @/*

If you chose the previous answer as “Yes”

Or you can customize those in the next.config.js file.

Configuring next.config.js

The next.config.js file is the main configuration file for a Next.js project. There, you can customize settings (environment variables, custom webpack configuration etc). Here’s a basic example:

// next.config.js
module.exports = {
  reactStrictMode: true,
  env: {
    CUSTOM_API_URL: 'https://api.example.com',
  },
  images: {
    domains: ['example.com'],
  },
  webpack: (config, { isServer }) => {
    // Modify the config here
    if (!isServer) {
      config.node = {
        fs: 'empty',
      };
    }
    return config;
  },
};

Explanation:

  • reactStrictMode: Activates strict mode in React for highlighting potential problems in your application.
  • env: Allows to define environment variables that can be accessed throughout the app.
  • images: Specifies domains from which images can be optimized and loaded.
  • webpack: Customize the Webpack configuration for both client and server builds.

Customizing the Build Process

Next.js allows customization of the build process through various scripts in your package.json. Example:

// package.json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  }
}

Explanation:

  • dev: Starts the development server.
  • build: Builds the application for production.
  • start: Starts the production server.
  • lint: Runs linting checks on your codebase.

Setting Up Aliases

Using aliases can simplify your import statements, making your code cleaner. This can be configured in the jsconfig.json or tsconfig.json file for and TypeScript projects, respectively.

// jsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@components/*": ["components/*"],
      "@lib/*": ["lib/*"]
    }
  }
}

Explanation:

  • baseUrl: Sets the base directory for resolving non-relative module names.
  • paths: Defines alias mappings for directories in your project.

Adding Plugins and Modules

Next.js supports various plugins and modules. For instance, to add Sass, you can install the necessary package and configure it:

npm install sass

Then, you can import Sass files directly in your components:

// components/Header.js
import '../styles/Header.module.scss';

const Header = () => (
  <header className="header">
    <h1>Welcome to My Next.js App</h1>
  </header>
);

export default Header;

Custom Server Configuration

Sometimes, you might need to customize the server behavior. Next.js allows you to create a custom server using Express.js or any other Node.js server framework. Here’s an example using Express:

// server.js
const express = require('express');
const next = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.get('/p/:id', (req, res) => {
    const actualPage = '/post';
    const queryParams = { id: req.params.id };
    app.render(req, res, actualPage, queryParams);
  });

  server.all('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(3000, (err) => {
    if (err) throw err;
    console.log('> Ready on http://localhost:3000');
  });
});

Explanation:

  • Initializes Next.js with Express.js.
  • Prepares the Next.js app.
  • Handles custom routes.
  • Starts the server on port 3000.

For more detailed configs, check out the official Next.js documentation.

Running the Development Server

To run a development instance of your new Next.js app (in other words, start your local development server), use the command:

npm run dev

This process is straightforward and gets you started in no time. Your terminal will display something like:

Local: http://localhost:3000
✔ Ready

From now on, you can start playing around with your app. Create components, set up routing, add styles, call APIs, whatever. Your app is in action, and all the changes you make will be visible in your browser by following the localhost address you got from Next.js. Once you’re done developing the features you want to see in your app, let’s proceed to the building process.

Building and Running in Production

Running your Next.js application in production requires building it first, for optimal performance, and then deploying it on a platform like Vercel, Netlify, or another hosting service.
To create an optimized build, use the following command:

npm run build

This command compiles your application and optimizes it for production, generating a .next directory with all the necessary files.
After running this command, you can start your application in production mode with:

npm start

Deploying on Vercel

Vercel is the company behind Next.js, thus it provides an excellent platform for deploying your Next.js apps. Deployment on Vercel is straightforward:

  • Sign up for Vercel.
  • Import your project: Connect your GitHub, GitLab, or Bitbucket repository to Vercel. Also, you can directly upload the “build” folder from your computer (the one you’ve got as a result of npm run build in your general projects folder).
  • Configure build settings: Vercel automatically detects Next.js projects and configures the build settings.
  • Deploy: Click "Deploy" and your application will be live.

For more detailed instructions, refer to the official Vercel documentation.

Deploying on Netlify

Netlify is another popular platform for deploying Next.js apps. Here’s how to deploy a Next.js app on Netlify:

  • Sign up for Netlify: Netlify Signup
  • Create a new site: Once logged in, click "New site from Git".
  • Connect your repository or upload a “build” folder from your local machine.
  • Deploy site: Click "Deploy site" and Netlify will start building your application.

For more detailed instructions, refer to the official Netlify documentation.

Configuring Environment Variables

Both Vercel and Netlify allow you to set environment variables for your application. These variables can be configured under the "Environment Variables" section.

Additional Hosting Options

You can also deploy your Next.js application on other platforms like AWS, Heroku, or DgitalOcean. The deployment process varies slightly between these services, but generally follows the same principles.

For more detailed instructions on deploying to other platforms, check the Next.js deployment documentation.

Conclusions

Still not sure about configuring and deploying your Next.js application or need some help? Trust us with your app. Perfsol never fails to deliver robust and scalable Next.js solutions. Whether you're facing challenges or need professional guidance, we’re here to help you every step of the way.

Mykola Breslavskyi
LinkedinLinkedin

Author

Mykola Breslavskyi

CTO

I am passionate about technologies. Adore solving challenges of our customers: going under the tech problem and trying to deal with a reason rather than a symptom. I do believe that is why our clients choose Perfsol.

Share this article


FacebookFacebook
LinkedinLinkedin

Drop us a message

attach file
Attach or drop file here

By sending a message you agree with your information being stored by us in relation to dealing with your enquiry. Please have a look at our Privacy Policy