Hurray!!! It's Day #20 of the #100daysofMiva coding challenge. Expect a check-in article into the last 10 days.
My goal today is to transition some of my projects from React and Vite to Next.js. It would've been seamless but for the build process that becomes complex and had to troubleshoot from time to time. Adjusting the package.json, editing new files/folder structures, deleting what's not necessary and making sure all new dependencies are rightly installed.
I researched more on Next.js for this article.
Introduction
React.js has been a cornerstone of modern web development for several years, offering developers a powerful, component-based architecture to build dynamic single-page applications (SPAs). However, as projects grow in complexity, developers often find themselves needing additional features that React.js alone cannot handle, such as server-side rendering (SSR), API routing, or seamless file-based routing. This is where Next.js comes in—a React.js framework that extends React with features like SSR, static site generation (SSG), and more.
So let's dive in to what Next.js is all about.
What is Next.js?
Next.js is an open-source React.js framework developed by Vercel that extends React’s capabilities by adding out-of-the-box features such as:
- Server-Side Rendering (SSR): Next.js renders pages on the server, improving performance and SEO.
- Static Site Generation (SSG): Pre-render static pages at build time, further improving performance.
- API Routes: Allows the creation of API endpoints in the same project without needing a separate backend.
- File-based Routing: Automatically creates routes based on the files in the pages directory, eliminating the need for external routing libraries like React Router.
- Hybrid Pages: Developers can combine SSR and SSG depending on the specific page's requirements.
These features are especially useful for websites that require strong SEO capabilities, dynamic content rendering, or hybrid approaches.
Transitioning from React.js to Next.js
If you have an existing React.js application, transitioning to Next.js is relatively straightforward. Next.js is built on top of React, so you can reuse most of your React components. The key differences lie in how routing, page rendering, and certain configurations are handled.
Steps to Migrate a React.js Project to Next.js
Install Next.js and Dependencies To start, you need to install Next.js and update your project’s dependencies.
npm install next react react-dom
This command installs the Next.js framework alongside React and React-DOM. React-DOM is necessary because Next.js uses the same React rendering engine for client-side components.
Modify package.json
In a React app, the package.json
typically looks like this:
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test"
}
Change it to the Next.js setup:
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
}
This tells Next.js to handle the dev server, build process, and production startup.
Restructure Your Project Files
/pages
index.js # Home page
about.js # About page
/clients
index.js # Client listing
[id].js # Dynamic route for each client
/components
Header.js
Footer.js
/public # For static assets (images, etc.)
Next.js uses a file-based routing system, where the structure of your pages
folder defines your routes. For example, a file named about.js
in the pages directory would automatically become accessible at /about
.
- Create a
pages
directory at the root of your project. - Move your existing React components into the
pages
directory as needed.
Convert Routing
If you’ve been using React Router in your React project, Next.js’s file-based routing will eliminate the need for react-router-dom. Here’s a simple example of how routing changes:
React Router:
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
<Router>
<Switch>
<Route path="/about" component={AboutPage} />
<Route path="/" component={HomePage} />
</Switch>
</Router>
);
}
Next.js File-based Routing:
- Simply create the files in the
pages
directory:-
pages/index.js
→ For the home page (/
). -
pages/about.js
→ For the About page (/about
). The routing is automatic, and you no longer need the externalreact-router-dom
package.
-
Server-Side Rendering (SSR) and Static Site Generation (SSG)
Next.js allows you to choose between SSR, SSG, or a combination of both for rendering pages. This flexibility can greatly improve your site's performance and SEO.
- SSR: Fetches data and renders the page on the server for every request.
export async function getServerSideProps() {
const data = await fetchData();
return { props: { data } };
}
- SSG: Pre-renders the page at build time.
export async function getStaticProps() {
const data = await fetchData();
return { props: { data } };
}
How React and Next.js Work Together
Let's talk about Component Usage
In Next.js, you still write your UI components using React. The JSX (JavaScript XML) syntax, state, and hooks like useState
, useEffect
, etc., are all the same in both React.js and Next.js projects.
Routing:
In React.js, you would typically use a library like react-router-dom for routing between pages. In Next.js, routing is file-based, meaning you create a file in the pages/
directory (e.g., about.js
), and it automatically becomes available at your-site.com/about
. No additional setup is required.
Rendering:
React.js by default is a client-side rendered library. Next.js, however, adds server-side rendering (SSR) and static site generation (SSG) as options. You can decide whether you want a page to be statically generated at build time or rendered on each request using SSR.
API Routes:
Next.js allows you to build backend logic within the same project using API routes. In a React.js app, you would need to build a separate backend, but with Next.js, you can create API endpoints directly in the pages/api/
directory.
Backend Compatibility: Best Backend Options for Next.js
Next.js is primarily a frontend framework, but it integrates seamlessly with various backend technologies. Here are some of the best backend frameworks to use with Next.js, based on our discussions:
Node.js (Express, Fastify, or NestJS)
Pros:
- Full-stack JavaScript environment.
- Seamless integration with Next.js's API routes.
- Wide community support.
Example:
npm install express
- Create an Express server in server.js
const express = require('express');
const next = require('next');
const app = next({ dev: true });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get('*', (req, res) => {
return handle(req, res);
});
server.listen(3000, (err) => {
if (err) throw err;
console.log('Server ready on http://localhost:3000');
});
});
Top comments (0)