Congratulations on setting up your first Next.js application! Now, let's get it running and explore how to navigate it.
The heart of running your Next.js application lies in its development server. This server provides several powerful features out of the box, including hot module replacement (HMR) for instant updates as you code, and server-side rendering (SSR) capabilities. To start this development server, open your terminal in the root directory of your Next.js project and run the following command:
npm run dev
# or
yarn devOnce you execute this command, Next.js will compile your application and start a local development server. You'll typically see output indicating the server is running on a specific port, usually http://localhost:3000.
Open your web browser and navigate to the address provided in your terminal (e.g., http://localhost:3000). You should see the default Next.js welcome page. This is your application running locally!
The beauty of the development server is its reactivity. Try editing a file, such as pages/index.js, and save it. You'll notice that your browser automatically refreshes to show the changes without you needing to manually reload. This is HMR in action, significantly speeding up your development workflow.
Next.js has a built-in file-system based router. This means that files inside the pages directory automatically become routes. For example, if you create a file named pages/about.js, you can access it by navigating to http://localhost:3000/about in your browser. Similarly, a file at pages/posts/first-post.js would be accessible at http://localhost:3000/posts/first-post.
Let's visualize how the pages directory maps to routes:
graph TD
A[pages/index.js] --> B(http://localhost:3000/)
C[pages/about.js] --> D(http://localhost:3000/about)
E[pages/products/index.js] --> F(http://localhost:3000/products)
G[pages/products/[id].js] --> H(http://localhost:3000/products/:id)
The [id].js example shows dynamic routing, where a part of the URL can be a variable. This is a powerful feature for creating pages with variable content, like individual product pages or user profiles.
To stop the development server, simply go back to your terminal where it's running and press Ctrl + C (or Cmd + C on macOS).
For production builds, you'll use a different command. This command optimizes your application for deployment, creating a highly efficient version. To build your application, use:
npm run build
# or
yarn buildAfter the build is complete, you can start a production-ready server with:
npm run start
# or
yarn startThis command starts a server optimized for performance and scalability. For most local development, however, npm run dev will be your go-to command.