← Back
NextJS Concepts
2025-06-01
#server-side #nextjs
File Based Routing
-
We can create routes using files. The
pages directory in a Next.js app is special.
pages/index.js will have the route of /
pages/mypage will have the route of /mypage
-
Any pages within a directory will include the directory name in their route.
- So if
mypage was contained in mydir then the route will be /mydir/mypage
-
Can use the
Link component for client-side routing
- Behaves like
<a> but doesn’t rerender the full page
- Example:
<Link href="mydir/myroute"></Link>
Project Assets (Images and Scripts)
- Static assets can be served from the
public directory and referenced like pages.
-
Next.js provides components to handle web-specific optimizations:
Image from 'next/image' handles resizing and optimization.
Script from 'next/script' optimizes third-party script loading with a strategy attribute and onLoad handlers.
Project Styling
-
Global CSS (loaded on every page):
- Create
pages/_app.js to import global CSS (no other way works).
- This file wraps all pages and helps maintain state and apply global styles.
-
Component-level CSS with CSS modules:
- Use
.module.css files for component styles.
- Import with alias:
import styles from '../../file.module.css'
- Apply styles via
className: <section className={styles.container}></section>
Next.js Pre-Rendering
- By default, Next.js pre-renders every page (HTML generated in advance).
- The browser runs the JS and "hydrates" the page when loaded.
- Two types of pre-rendering:
- Static Generation
- HTML is built at compile time and reused.
- Ideal for content that doesn’t change per request.
- Use
getStaticProps to fetch required data.
- Server-Side Rendering
- HTML is generated on each request.
- Use
getServerSideProps for dynamic content.
- You can use both strategies in the same app (hybrid).
Statically Generate Dynamic Routes
- Create a dynamic page using square brackets, e.g.
[id].js
- Use
getStaticPaths to return all possible id values
- Return an object with a
params key, matching the filename param.
- Use
getStaticProps to fetch data based on the id.
getStaticPaths supports a fallback option:
false = 404 if path not returned by getStaticPaths.
true = Next.js renders fallback while generating the page.
- Workflow: use
getStaticPaths for ids, and getStaticProps for data per id.