{"id":22688329,"url":"https://github.com/emanuelefavero/next-js","last_synced_at":"2025-04-22T15:10:51.424Z","repository":{"id":65407919,"uuid":"590857743","full_name":"emanuelefavero/next-js","owner":"emanuelefavero","description":"A Next.js cheat sheet repository","archived":false,"fork":false,"pushed_at":"2023-01-28T01:25:53.000Z","size":45,"stargazers_count":66,"open_issues_count":0,"forks_count":16,"subscribers_count":3,"default_branch":"main","last_synced_at":"2025-03-29T16:13:38.707Z","etag":null,"topics":["cheatsheet","javascript","next","nextjs","react"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/emanuelefavero.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2023-01-19T11:31:11.000Z","updated_at":"2025-03-05T06:48:47.000Z","dependencies_parsed_at":"2023-02-12T14:16:15.135Z","dependency_job_id":null,"html_url":"https://github.com/emanuelefavero/next-js","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fnext-js","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fnext-js/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fnext-js/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/emanuelefavero%2Fnext-js/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/emanuelefavero","download_url":"https://codeload.github.com/emanuelefavero/next-js/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":250264909,"owners_count":21402004,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","javascript","next","nextjs","react"],"created_at":"2024-12-10T00:13:51.838Z","updated_at":"2025-04-22T15:10:51.397Z","avatar_url":"https://github.com/emanuelefavero.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Next JS\n\nA Next.js cheat sheet repository\n\n## Example Projects\n\n| Project                                    | Description                             |\n| ------------------------------------------ | --------------------------------------- |\n| [next-js-example-app](next-js-example-app) | A bare-bone example app with local data |\n\n## Table of Contents\n\n- [Create a new Next.js app](#create-a-new-nextjs-app)\n- [ESLint](#eslint)\n- [Manual Installation](#manual-installation)\n- [Folder Structure](#folder-structure)\n- [Routing](#routing)\n- [Meta tags](#meta-tags)\n- [The `_app.js` file](#the-_appjs-file)\n- [The `Layout` component](#the-layout-component)\n- [Sass](#sass)\n- [Tailwind CSS](#tailwind-css)\n- [Styled JSX](#styled-jsx)\n- [The `_document.js` file](#the-_documentjs-file)\n- [The `Image` component](#the-image-component)\n- [The `Script` component](#the-script-component)\n- [Fetch data](#fetch-data)\n- [Example of using `getStaticPaths` and `getStaticProps` together](#example-of-using-getstaticpaths-and-getstaticprops-together)\n- [Fetch Data on the client](#fetch-data-on-the-client)\n- [SWR](#swr)\n- [When to use **Static Generation** v.s. **Server-side Rendering**](#when-to-use-static-generation-vs-server-side-rendering)\n- [Dynamic routes](#dynamic-routes)\n- [Custom 404 pages](#custom-404-pages)\n- [Export Static Site](#export-static-site)\n- [API Routes](#api-routes)\n- [Check for `development` mode or `production` mode](#check-for-development-mode-or-production-mode)\n- [Custom Meta Component](#custom-meta-component)\n- [useRouter Hook](#userouter-hook)\n- [useRouter Redirect](#userouter-redirect)\n- [Redirects](#redirects)\n\n## Create a new Next.js app\n\n```bash\nnpx create-next-app\n```\n\n### Use TypeScript, ESLint and npm\n\n```bash\nnpx create-next-app --typeScript --eslint --use-npm\n```\n\n## ESLint\n\nAdd the following to the `.eslintrc.json` file\n\n```json\n{\n  // \"extends\": [\"next/core-web-vitals\"]\n  \"root\": true,\n  \"parser\": \"@typescript-eslint/parser\",\n  \"plugins\": [\"@typescript-eslint\"],\n  \"extends\": [\n    \"plugin:@next/next/recommended\",\n    \"eslint:recommended\",\n    \"plugin:@typescript-eslint/eslint-recommended\",\n    \"plugin:@typescript-eslint/recommended\"\n  ],\n  \"parserOptions\": {\n    \"ecmaVersion\": 2020\n  },\n\n  \"env\": {\n    \"es6\": true\n  }\n}\n```\n\n## Manual Installation\n\n- Add Next.js to your project\n\n```bash\nnpm install next react react-dom\n```\n\n- Add the following scripts to your package.json\n\n```json\n\"scripts\": {\n  \"dev\": \"next dev\",\n  \"build\": \"next build\",\n  \"start\": \"next start\",\n  \"lint\": \"next lint\"\n}\n```\n\n## Folder Structure\n\n**Pages folder** - is the only required folder in a Next.js app. All the React components inside pages folder will automatically become routes\n\n\u003e Note: The name of the file will be the route name, use lowercase for the file name and PascalCase for the component name\n\n**Public folder** - contains static assets such as images, files, etc. The files inside public folder can be accessed directly from the root of the application\n\n**Styles folder** - contains stylesheets, here you can add global styles, CSS modules, etc\n\n\u003e Usually `globals.css` is imported in the `_app.js` file\n\n**Components folder** - contains React components\n\n### The `@` alias\n\nThe `@` alias is used to import files from the root of the project\n\n```jsx\nimport Header from '@/components/Header'\n```\n\nTo use the `@` alias, add the following to the `jsconfig.json` file at the root of the project\n\n```json\n{\n  \"compilerOptions\": {\n    \"baseUrl\": \".\",\n    \"paths\": {\n      \"@/*\": [\"*\"]\n    }\n  }\n}\n```\n\n## Routing\n\n- **Link** - is used for client-side routing. It is similar to the HTML `\u003ca\u003e` tag\n\n```jsx\nimport Link from 'next/link'\n\nexport default function Home() {\n  return (\n    \u003cdiv\u003e\n      \u003cLink href='/about'\u003eAbout\u003c/Link\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n## Meta tags\n\n- **Head** - is used to add meta tags to the page\n\n```jsx\nimport Head from 'next/head'\n\nexport default function Home() {\n  return (\n    \u003cdiv\u003e\n      \u003cHead\u003e\n        \u003ctitle\u003eMy page title\u003c/title\u003e\n        \u003cmeta name='description' content='Generated by create next app' /\u003e\n        \u003clink rel='icon' href='/favicon.ico' /\u003e\n      \u003c/Head\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n\u003e The `Head` component should be placed inside the `Layout` component or inside the `_app.js` file\n\n### Give a different title to each page\n\n- Import the `Head` component and put the `title` tag inside it\n\n## The `_app.js` file\n\nWrap around each page and here is where you would import global styles and put header and footer components\n\n\u003e Note: You could also put the header and footer components inside the `Layout` component\n\n## The `Layout` component\n\n- Create a `Layout` component and wrap around each page with children prop\n\n```jsx\nimport Header from '@/components/Header'\nimport Footer from '@/components/Footer'\n\nexport default function Layout({ children }) {\n  return (\n    \u003cdiv\u003e\n      \u003cHeader /\u003e\n      {children}\n      \u003cFooter /\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n- Import the `Layout` component in the `_app.js` file\n\n```jsx\nimport Layout from '@/components/Layout'\n\nfunction MyApp({ Component, pageProps }) {\n  return (\n    \u003cLayout\u003e\n      \u003cComponent {...pageProps} /\u003e\n    \u003c/Layout\u003e\n  )\n}\n\nexport default MyApp\n```\n\n## Sass\n\nNext.js has built-in support for Sass\n\n- Install `sass`\n\n```bash\nnpm i -D sass\n```\n\n## Tailwind CSS\n\n- Install `tailwindcss`\n\n```bash\nnpm install -D tailwindcss autoprefixer postcss\n```\n\n- Create a `tailwind.config.js` file at the root of the project\n\n```bash\nmodule.exports = {\n  content: [\n    './pages/**/*.{js,ts,jsx,tsx}',\n    './components/**/*.{js,ts,jsx,tsx}',\n  ],\n  theme: {\n    extend: {},\n  },\n  plugins: [],\n}\n```\n\n\u003e Note: If you are using the `src` folder, change the path to `./src/pages/**/*.{js,ts,jsx,tsx}` and `./src/components/**/*.{js,ts,jsx,tsx}`\n\n- Create a `postcss.config.js` file at the root of the project\n\n```bash\nmodule.exports = {\n  plugins: {\n    tailwindcss: {},\n    autoprefixer: {},\n  },\n}\n```\n\n- Add the following to `globals.css`\n\n```css\n@tailwind base;\n@tailwind components;\n@tailwind utilities;\n```\n\n- Import `globals.css` in the `_app.js` file\n\n```jsx\nimport '@/styles/globals.css'\n```\n\n## Styled JSX\n\nStyled JSX is a CSS-in-JS library that allows you to write CSS inside a React component\n\nIt has two modes: global and scoped\n\n- **Global** - styles are applied globally to the entire application\n\n```jsx\nexport default function Home() {\n  return (\n    \u003c\u003e\n      Your JSX here\n      \u003cstyle jsx global\u003e{`\n        p {\n          color: red;\n        }\n      `}\u003c/style\u003e\n    \u003c/\u003e\n  )\n}\n```\n\n- **Scoped** - styles are applied only to the component\n\n```jsx\nexport default function Home() {\n  return (\n    \u003c\u003e\n      Your JSX here\n      \u003cstyle jsx\u003e{`\n        p {\n          color: red;\n        }\n      `}\u003c/style\u003e\n    \u003c/\u003e\n  )\n}\n```\n\n\u003e Note: If in vs-code the syntax highlighting for the `style` tag is not working, you can install the `vscode-styled-components` extension to fix this\n\u003e\n\u003e Be sure that the curly braces are on the same line as the `style` tag: `\u003cstyle jsx\u003e{`\n\u003e\n\u003e No need to use styled jsx if you use other methods like CSS modules or styled components\n\n## The `_document.js` file\n\nHere you can customize the `html` and `body` tags\n\n\u003e For instance you can add a `lang` attribute to the `html` tag\n\n```jsx\nimport Document, { Html, Head, Main, NextScript } from 'next/document'\n\nexport default function Document() {\n  return (\n    \u003cHtml lang='en'\u003e\n      \u003cHead /\u003e\n      \u003cbody\u003e\n        \u003cMain /\u003e\n        \u003cNextScript /\u003e\n      \u003c/body\u003e\n    \u003c/Html\u003e\n  )\n}\n```\n\n\u003e Note: This file will be created if you create a new Next.js app with `npx create-next-app`\n\n## The `Image` component\n\nYou can use the `Image` component to add images\n\n\u003e The images will be optimized automatically\n\n```jsx\nimport Image from 'next/image'\n\nexport default function Home() {\n  return (\n    \u003cdiv\u003e\n      \u003cImage src='/images/profile.jpg' width={144} height={144} /\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n\u003e Note: src, width and height are required, alt is recommended\n\n- if you use a remote image, you need to add the domain to the `next.config.js` file\n\n```bash\nimages: {\n    domains: ['images.pexels.com'],\n  },\n```\n\n- or in Next.js 12.4.0:\n\n```bash\nimages: {\n    remotePatterns: [\n      {\n        protocol: 'https',\n        hostname: 'example.com',\n        port: '',\n        pathname: '/account123/**',\n      },\n    ],\n  },\n```\n\n## The `Script` component\n\nYou can use the `Script` component to add scripts\n\n```jsx\nimport Script from 'next/script'\n\nexport default function Home() {\n  return (\n    \u003cdiv\u003e\n      \u003cScript src='https://code.jquery.com/jquery-3.6.0.min.js' /\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n\u003e Note: you can add cdn scripts as well as local scripts in the `public` folder\n\n## Fetch Data\n\nNext.js let's you choose how to fetch data for each page. It is advised to use `getStaticProps` for most of the pages and `getServerSideProps` for pages with frequently updated data\n\n- **getStaticProps** - is used to fetch data at build time\n\n\u003e Note: During development with `npm run dev`, `getStaticProps` runs on every request\n\u003e\n\u003e `getStaticProps` can only be exported from a page. You can't export it from non-page files\n\n```jsx\nexport async function getStaticProps() {\n  const res = await fetch('https://.../posts')\n  const posts = await res.json()\n\n  return {\n    props: {\n      posts,\n    },\n  }\n}\n```\n\n\u003e `posts` will be passed to the component as a prop:\n\n```jsx\nexport default function Home({ posts }) {\n  return (\n    \u003cdiv\u003e\n      {posts.map((post) =\u003e (\n        \u003ch3\u003e{post.title}\u003c/h3\u003e\n      ))}\n    \u003c/div\u003e\n  )\n}\n```\n\n- **getStaticPaths** - is used to specify dynamic routes to pre-render pages based on data\n\n```jsx\nexport async function getStaticPaths() {\n  const res = await fetch('https://.../posts')\n  const posts = await res.json()\n\n  const paths = posts.map((post) =\u003e ({\n    params: { id: post.id },\n  }))\n\n  return { paths, fallback: false }\n}\n```\n\n\u003e Note: When `fallback` is `false`, any paths not returned by `getStaticPaths` will result in a 404 page\n\u003e\n\u003e If `fallback` is `true`, then when a user visit a page that is not pre-rendered, Next.js will generate the page on the fly and return it to the user (useful for sites with frequently updated data like a social network)\n\n- **getServerSideProps** - is used to fetch data on the server on each request\n\n```jsx\nexport async function getServerSideProps(context) {\n  return {\n    props: {\n      // props for your component\n    },\n  }\n}\n```\n\n\u003e `getStaticProps` and `getServerSideProps` have a `context` parameter that contains the url `params` object\n\u003e\n\u003e You can use this to fetch data for a specific post (e.g. `context.params.id`)\n\n### Example of using `getStaticPaths` and `getStaticProps` together\n\nUse `getStaticPaths` to fetch an array of IDs and use `getStaticProps` to fetch data for each product based on the ID\n\n```jsx\nexport async function getStaticPaths() {\n  const res = await fetch('https://.../posts')\n  const posts = await res.json()\n\n  const paths = posts.map((post) =\u003e ({\n    params: { id: post.id },\n  }))\n\n  return { paths, fallback: false }\n}\n\nexport async function getStaticProps({ params }) {\n  const res = await fetch(`https://.../posts/${params.id}`)\n  const post = await res.json()\n\n  return {\n    props: {\n      post,\n    },\n  }\n}\n```\n\n## Fetch Data on the client\n\n\u003e Sometimes it can be beneficial to fetch data on the client instead of on the server.\n\u003e\n\u003e For example, you could fetch all the static data on the server and then fetch the dynamic data on the client such as a user-specific data that changes frequently and is not needed for SEO.\n\n- **useEffect** - is used to fetch data on the client\n\n```jsx\nimport { useEffect, useState } from 'react'\n\nexport default function Home() {\n  const [posts, setPosts] = useState([])\n\n  useEffect(() =\u003e {\n    fetch('https://.../posts')\n      .then((res) =\u003e res.json())\n      .then((data) =\u003e setPosts(data))\n  }, [])\n\n  return (\n    \u003cdiv\u003e\n      {posts.map((post) =\u003e (\n        \u003ch3 key={post.id}\u003e{post.title}\u003c/h3\u003e\n      ))}\n    \u003c/div\u003e\n  )\n}\n```\n\n## SWR\n\n\u003e SWR is a React Hooks library for remote data fetching on the client\n\u003e\n\u003e You should use it instead of `useEffect`\n\n```jsx\nimport useSWR from 'swr'\n\nexport default function Home() {\n  const { data, error } = useSWR('api/user', fetch)\n\n  if (error) return \u003cdiv\u003efailed to load\u003c/div\u003e\n  if (!data) return \u003cdiv\u003eloading...\u003c/div\u003e\n\n  return (\n    \u003c\u003e\n      {data.map((post) =\u003e (\n        \u003ch3 key={post.id}\u003e{post.title}\u003c/h3\u003e\n      ))}\n    \u003c/\u003e\n  )\n}\n```\n\n## When to use **Static Generation** v.s. **Server-side Rendering**\n\nUse Static Generation whenever possible because it's much faster than Server-side Rendering and the page can be served by CDN.\n\nYou should ask yourself:\n\n- Can I pre-render this page ahead of a user's request?\n\nIf the answer is yes, then you should choose Static Generation.\n\n- Does the page need to update frequently?\n\nIf the answer is yes, then you should choose Server-side Rendering.\n\nYou can use Static Generation for many types of pages, including:\n\n- Marketing pages\n- Blog posts\n- E-commerce product listings\n- Help and documentation\n\nYou could also skip Server-side Rendering and use client-side JavaScript to fetch data with `useEffect`\n\n## Dynamic Routes\n\n- Create a folder inside the `pages` folder with the name of the dynamic route in square brackets (e.g. `[id]`)\n\n- Create an `index.js` file inside the dynamic route folder\n\n### Dynamic Links\n\n- Create a link with that points to the dynamic route and pass the dynamic value as a prop\n\n```jsx\nimport Link from 'next/link'\n\nexport default function Post({ post }) {\n  return (\n    \u003cdiv\u003e\n      \u003cLink href='/posts/[id]' as={`/posts/${post.id}`}\u003e\n        \u003ca\u003e{post.title}\u003c/a\u003e\n      \u003c/Link\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n\u003e Note: this is usually done inside a `map` function\n\n### Catch All Routes\n\nDynamic routes can be extended to catch all paths by adding three dots (...) inside the brackets. For example:\n\n- `pages/posts/[...id].js` matches `/posts/a`, but also `/posts/a/b`, `/posts/a/b/c` and so on.\n\nIf you do this, in getStaticPaths, you must return an array as the value of the id key like so:\n\n```jsx\nreturn [\n  {\n    params: {\n      // Statically Generates /posts/a/b/c\n      id: ['a', 'b', 'c'],\n    },\n  },\n  //...\n]\n```\n\nAnd params.id will be an array in getStaticProps:\n\n```jsx\nexport async function getStaticProps({ params }) {\n  // params.id will be like ['a', 'b', 'c']\n}\n```\n\n## Custom 404 pages\n\n- Create a `404.js` file inside the `pages` folder\n\n```jsx\nexport default function Custom404() {\n  return \u003ch1\u003e404 - Page Not Found\u003c/h1\u003e\n}\n```\n\n\u003e Note: You can also create a `500.js` file for the server error page\n\n## Export Static Site\n\nExport a static site with `next export`\n\n\u003e Add an npm script to the `package.json` file:\n\n```json\n\"scripts\": {\n  \"export\": \"next build \u0026\u0026 next export\"\n}\n```\n\n\u003e Run the script:\n\n```bash\nnpm run export\n```\n\n\u003e The static site will be exported to the `out` folder\n\u003e\n\u003e You can deploy this folder to any static site host such as GitHub Pages\n\n#### Build a local server to test the static site\n\n- Install `serve`\n\n```bash\nnpm i -g serve\n```\n\n- Run the server\n\n```bash\nserve -s out -p 8000\n```\n\n## API Routes\n\nYou can work with any database in the `pages/api/` folder\n\n\u003e Note: Any API route that is placed inside this folder will be accessible like any other page in Next.js\n\n- Create a folder inside the `pages` folder with the name of the API route (e.g. `api/posts`)\n\n### Work with local data\n\n- Create a `data.js` file at the root of the project\n\n```js\nconst posts = [\n  {\n    id: 1,\n    title: 'Post 1',\n  },\n  {\n    id: 2,\n    title: 'Post 2',\n  },\n  {\n    id: 3,\n    title: 'Post 3',\n  },\n]\n```\n\n- Import the data in the API route\n\n```js\nimport { posts } from '@/data'\n```\n\n- Get the data\n\n```js\nexport default function handler(req, res) {\n  res.status(200).json(posts)\n}\n```\n\n\u003e You can now fetch the data as you would with any other API\n\u003e\n\u003e Note: Next.js needs absolute paths when fetching data\n\n## Check for `development` mode or `production` mode\n\nSince Next.js needs absolute paths when fetching data, you can check if you are in `development` mode or `production` mode\n\n- Create a `config.js` folder at the root of the project with an `index.js` file inside\n\n```js\nconst dev = process.env.NODE_ENV !== 'production'\n\nexport const server = dev ? 'http://localhost:3000' : 'https://yourwebsite.com'\n```\n\n- Now you can use `server` as a variable in your code as an absolute path when fetching data\n\n```js\nimport { server } from '@/config'\n\nexport default function handler(req, res) {\n  fetch(`${server}/api/posts`)\n    .then((res) =\u003e res.json())\n    .then((data) =\u003e res.status(200).json(data))\n}\n```\n\n## Custom Meta Component\n\n\u003e Note: There is no need to create a custom meta component since we can use the `Head` component from Next.js\n\nA meta component is used to add meta tags to the `head` of the document\n\n- Create a `Meta.js` file inside the `components` folder\n\n```jsx\nimport Head from 'next/head'\n\nexport default function Meta({ title, keywords, description }) {\n  return (\n    \u003cHead\u003e\n      \u003cmeta charSet='utf-8' /\u003e\n      \u003cmeta name='viewport' content='width=device-width, initial-scale=1' /\u003e\n      \u003clink rel='icon' href='/favicon.ico' /\u003e\n      \u003cmeta name='keywords' content={keywords} /\u003e\n      \u003cmeta name='description' content={description} /\u003e\n      \u003ctitle\u003e{title}\u003c/title\u003e\n    \u003c/Head\u003e\n  )\n}\n```\n\n\u003e Tip: You can also use packages such as `next-seo` for this\n\n- Add `defaultProps` to the `Meta` component so that you don't need to add props to it every time you use it\n\n```jsx\nMeta.defaultProps = {\n  title: 'WebDev News',\n  keywords: 'web development, programming',\n  description: 'Get the latest news in web dev',\n}\n```\n\n- Now you can use the `Meta` component in any page (it is common to use it in the `Layout` component)\n\n```jsx\nimport Meta from '@/components/Meta'\n\nexport default function Layout({ children }) {\n  return (\n    \u003cdiv\u003e\n      \u003cMeta /\u003e\n      {children}\n    \u003c/div\u003e\n  )\n}\n```\n\n### Add a specific title to a page\n\n- Import the `Meta` component in the specific page and pass the title as a prop\n\n```jsx\nimport Meta from '@/components/Meta'\n\nexport default function About() {\n  return (\n    \u003cdiv\u003e\n      \u003cMeta title='About' /\u003e\n      \u003ch1\u003eWelcome to the About Page\u003c/h1\u003e\n    \u003c/div\u003e\n  )\n}\n```\n\n## \u0026nbsp;\n\n## useRouter Hook\n\nuseRouter is a hook that gives you access to the router object\n\n- Import the `useRouter` hook\n\n```jsx\nimport { useRouter } from 'next/router'\n```\n\n- Use the `useRouter` hook\n\n```jsx\nconst router = useRouter()\n```\n\n- Get the query\n\n```jsx\nconst router = useRouter()\nconst { query } = router\n```\n\n- Get the query with destructuring\n\n```jsx\nconst {\n  query: { id },\n} = useRouter()\n```\n\nuseRouter main properties:\n\n- `pathname` - Current route. That is the path of the page in `pages`\n- `route` - Current route with the query string\n- `query` - Query string section of URL parsed as an object\n- `asPath` - String of the actual path (including the query) shown in the browser\n\n## useRouter Redirect\n\n- Import the `useRouter` hook\n\n```jsx\nimport { useRouter } from 'next/router'\n```\n\n- Use the `useRouter` hook to redirect the user to home page\n\n```jsx\nconst router = useRouter()\nrouter.push('/')\n```\n\n\u003e Note: You can for instance use this hook in a `404` page to redirect the user to the home page after 3 seconds\n\n## Redirects\n\nTo redirect a user to another page, you can use `redirects` on `next.config.js`\n\n```js\nmodule.exports = {\n  async redirects() {\n    return [\n      {\n        source: '/about',\n        destination: '/',\n        permanent: false,\n      },\n    ]\n  },\n}\n```\n\n\u003e Note: `permanent: true` will tell the browser to cache the redirect forever. That means that if the user goes to the `/about` page, the browser will redirect the user to the `/` page without making a request to the server\n\u003e\n\u003e TIP: Do not use `permanent: true` for redirects that are not permanent\n\n### Redirects HTTP status codes\n\n- `308` - Permanent Redirect\n- `307` - Temporary Redirect\n\n\u003e Note: `308` replaces `301`, `307` replaces `302`\n\n\u0026nbsp;\n\n---\n\n\u0026nbsp;\n\n[**Go To Top \u0026nbsp; ⬆️**](#next-js)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femanuelefavero%2Fnext-js","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Femanuelefavero%2Fnext-js","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Femanuelefavero%2Fnext-js/lists"}