Brief Introduction

What is NextJS

  • ​A React Framework
  • A SSG (Static Site Generator)


  1. Hybrid: use as SSG, or for SSR, or both
  2. File Based Routing: Anything inside pages is a route
  3. Built in CSS and SASS Support
  4. API Routes
  5. Zero Config
  6.  Asset Optimizations (Image, CSS, JS etc)


Any route(page) in the pages directory can be exported statically (HTML+minimal CSS&JS) Use `getStaticProps` fetch data at Build time and pass data as prop ``` export async function getStaticProps() { const allPostsData = getSortedPostsData() return { props: { allPostsData } } }


Generate the routes Dynamically with `getStaticPaths` ``` export async function getStaticPaths() { return { paths: [ { params: { ... } } // See the "paths" section below ], fallback: true or false // See the "fallback" section below }; } ```


If a page export function named `getServerSideProps`, SSR is enabled for that page PreRendering of page will be done on every request with the data received from above function ``` export async function getServerSideProps(context) { return { props: {}, // will be passed to the page component as props } } ``` `context` hold `req`, `res`, `path`, `queryString` etc


### Static Routes `pages/index.js` → `/` `pages/posts/index.js` → `/posts` --- ### [Dynamic Routes]( `pages/blog/[slug].js` → `/blog/:slug` (`/blog/hello-world` when `slug` is `hello-world`) `pages/[user]/settings.js` → `/:user/settings` (`/foo/settings` when `user` is `foo`) `pages/post/[...all].js` → `/post/*` (`/post/2020/id/title`)

API Routes

Any file inside `pages/api` is a API route. API Route file as the following signature: ``` export default function handler(req, res) { if (req.method === 'POST') { // Process a POST request } else { // Handle any other HTTP method res.status(200).json({ name: 'John Doe' }) } } ``` Dynamic API route work in same way as Dynamic Page Routes with re

API Routes: Middleware

Route Middleware with exported object `config` ``` export const config = { api: { bodyParser: { sizeLimit: '500kb' }, }, } ``` Though custom middleware can also be added; [Read more here](

API Routes: Response Helpers

`res` object has certain API to help with response. Eg: `res.send` send string or Buffer or object `res.status` send status code for the response `res.json` send JSON response `res.redirect` redirect with status code (optional, defaults to 307) to a path

When to choose Next.js?

→ Almost zero config → Next provides API routes, which allows proxying. If you want to proxy API in your FrontEnd → SSG, a easy replacement of GatsbyJS and no GraphQL knowledge needed → SSR and Hybrid Development TS, SASS, CSS Modules support


Pankaj Patel