Next JS code snippets from basics to advanced that we should know
In this article, we will go through some basics and advanced code snippets that we should know before start working in Next JS. These will be helpful while working in Next JS. Let’s start -
1. Creating a New Next.js App
npx create-next-app@latest my-next-app
cd my-next-app
npm run dev
This command initializes a new Next.js project using create-next-app
, a tool that sets up a new Next.js application with a default structure and configuration. npm run dev
starts the development server.
2. Basic Page Component
// pages/index.js
export default function Home() {
return (
<div>
<h1>Welcome to Next.js!</h1>
</div>
);
}
This is a simple React component that serves as the homepage of your Next.js application. It renders a div
containing a welcome message.
3. Linking Between Pages
import Link from 'next/link';
export default function Home() {
return (
<div>
<h1>Welcome to Next.js!</h1>
<Link href="/about">
<a>About Page</a>
</Link>
</div>
);
}
This snippet demonstrates how to navigate between pages in a Next.js application using the Link
component. Clicking the link navigates to the /about
page.
4. Fetching Data with getStaticProps
// pages/index.js
export async function getStaticProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: {
data,
},
};
}
export default function Home({ data }) {
return (
<div>
<h1>Data from API</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
getStaticProps
is a Next.js function used to fetch data at build time. The fetched data is passed as props to the page component, which can then render it. This is useful for static site generation (SSG).
5. Dynamic Routes
// pages/posts/[id].js
import { useRouter } from 'next/router';
export default function Post() {
const router = useRouter();
const { id } = router.query;
return <p>Post: {id}</p>;
}
This snippet shows how to create dynamic routes in Next.js. The [id].js
file in the pages/posts
directory will match any URL like /posts/1
, /posts/2
, etc. The useRouter
hook is used to access the dynamic route parameter.
6. API Routes
// pages/api/hello.js
export default function handler(req, res) {
res.status(200).json({ text: 'Hello' });
}
This snippet defines an API route in Next.js. The function handles HTTP requests to /api/hello
and responds with a JSON object. API routes allow you to create backend endpoints within your Next.js application.
7. Custom _app.js
for Global Styles
// pages/_app.js
import '../styles/globals.css';
export default function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />;
}
The _app.js
file is used to customize the default App component in Next.js. This example imports global CSS styles and applies them to all pages in the application.
8. Server-Side Rendering with getServerSideProps
// pages/index.js
export async function getServerSideProps() {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: {
data,
},
};
}
export default function Home({ data }) {
return (
<div>
<h1>Data from API</h1>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
}
getServerSideProps
is used to fetch data on each request. This function runs on the server side and passes the fetched data as props to the page component. It's useful for server-side rendering (SSR).
9. API Middleware
// pages/api/middleware.js
import { NextResponse } from 'next/server';
export function middleware(req) {
const url = req.nextUrl.clone();
if (url.pathname === '/api/restricted') {
return NextResponse.redirect('/api/hello');
}
return NextResponse.next();
}
This snippet demonstrates how to create middleware for API routes in Next.js. Middleware can be used to intercept requests and perform actions like redirects or authentication checks before the request reaches the API route handler.