These are some notes about NextJs I use as a cheatcheet when developing React applications with NextJs.

15t Path source: G:\APPS\NEXTJS

Get Started:

1. Create nextjs app with tailwind: (SEE: Next.js, & Tailwind CSS)
npx create-next-app -e with-tailwindcss name-of-app

2. Out of the box, without configuration, Next.js compiles CSS using PostCSS.
$ npm install -D tailwindcss autoprefixer postcss

3. Start Development Server:
$ npm run dev

4. Open application in browser:
ready - started server on 0.0.0.0:3000, url: http://localhost:3000

5. Build your app
$ npm run build

  • This will build a .next directory. If you need to create a custom directory such as as a build/ directory, See instructions how to setup custom build directory  and Deploy your build
  • You can specify the name of the .next directory to use instead of build for example, to do so, open next.config.js and add the distDir to module.exports:
  • module.exports = {
      reactStrictMode: true,
      distDir: 'build',
    }
  • Build to a static host: (example: index.html) To create a static build with nextjs, you will have to perform a couple of extra steps: More help on Static HTML Export
  • Open package.json and change build to:
  • "build": "next build && next export",
  • Now when you run npm run build, it will create a out directory which contains an index.html file and all the necessary files.

6. Run your build on whatever you choose:
$ npm run start -p 8080

NextJs Forms:

Follow this really good tutorial on form submissions

Notes:

https://nextjs.org/docs/getting-started

https://www.freecodecamp.org/news/nextjs-tutorial/#what-is-next-js
npx create-next-app my-next-project

https://www.freecodecamp.org/news/nextjs-tutorial/#what-is-next-js

npx create-next-app my-next-project

npm run dev

https://nextjs.org/learn/basics/create-nextjs-app/setup

npx create-next-app nextjs-blog --use-npm --example "https://github.com/vercel/next-learn/tree/master/basics/learn-starter"

cd nextjs-blog

code .

npm run dev

#LINKS:


regular: <a href="https://nextjs.org">Next.js!</a>

USAGE:


        <h1 className="title">
        {/* {' '} adds an empty space, which is used to divide text over multiple lines. */}
          Read{' '}
          <Link href="/posts/first-post">
            <a>this page!</a>
          </Link>
        </h1>



The public directory is also useful for robots.txt, Google Site Verification, and any other static assets. Check out the documentation for Static File Serving to learn more.
https://nextjs.org/docs/basic-features/static-file-serving


################################### IMAGE;###################################
Note: next/image requires Next.js 10 or later.

public/images


<img src="/images/profile.jpg" alt="Your Name" />

import Image from 'next/image';
<Image
    src="/images/profile.jpg" // Route of the image file
    height={144} // Desired size with correct aspect ratio
    width={144} // Desired size with correct aspect ratio
    alt="Your Name"
  />



  ########################### #HEAD ###################################
  https://nextjs.org/learn/basics/assets-metadata-css/metadata


      <Head>
  <title>First Post</title>
  <link rel="icon" href="/favicon.ico" />
  <script src="https://connect.facebook.net/en_US/sdk.js" />
</Head>

SCRIPT IN HEAD
import Script from 'next/script';
        <Script
          src="https://connect.facebook.net/en_US/sdk.js"
          strategy="lazyOnload"
          onLoad={() =>
            console.log(`script loaded correctly, window.FB has been populated`)
          }
        />



########################### STYLE ###################################

<style jsx>{`
  …
`}</style>



########################### Components ###################################
import Layout from '../../components/layout';

</Layout>
########################### CSS FILE ###################################
create file in src/components/layout.module.css

ofuscate css hide transform change encrypt clash


This is what CSS Modules does: It automatically generates unique class names. As long as you use CSS Modules, you don’t have to worry about class name collisions.

layout.module.css:
.container {
    max-width: 36rem;
    padding: 0 1rem;
    margin: 3rem auto 6rem;
  }
 
import styles from './layout.module.css';

<div className={styles.container}></div>



in browswer will generate something like this: <div class="__34hdt"></div>
########################### Global Styles ###################################
https://nextjs.org/learn/basics/assets-metadata-css/global-styles

pages/_app.js

This App component is the top-level component which will be common across all the different pages. You can use this App component to keep state when navigating between pages, for example.

IMPORTANT: You need to restart the development server when you add pages/_app.js.

In Next.js, you can add global CSS files by importing them from pages/_app.js. You cannot import global CSS anywhere else

########################### Using classnames library to toggle classes ###################################
https://nextjs.org/learn/basics/assets-metadata-css/styling-tips
classnames is a simple library that lets you toggle class names easily. You can install it using npm install classnames or yarn add classnames.


########################### TAILWINDS ###################################
Out of the box, with no configuration, Next.js compiles CSS using PostCSS.

npm install -D tailwindcss autoprefixer postcss



########################### Pre-rendering ###################################
https://nextjs.org/learn/basics/data-fetching/pre-rendering



########################### Static Generation and Server-side Rendering ###################################
   https://nextjs.org/learn/basics/data-fetching/two-forms
    Static Generation is the pre-rendering method that generates the HTML at build time. The pre-rendered HTML is then reused on each request.
    Server-side Rendering is the pre-rendering method that generates the HTML on each request.

 for some pages, you might not be able to render the HTML without first fetching some external data. Maybe you need to access the file system, fetch external API, or query your database at build time. Next.js supports this case — Static Generation with data — out of the box.


########################### getStaticProps ###################################

########################### YAML Front Matter ###################################
https://nextjs.org/learn/basics/data-fetching/blog-data
You might have noticed that each markdown file has a metadata section at the top containing title and date. This is called YAML Front Matter, which can be parsed using a library called gray-matter.



########################### gray-matter ###################################
npm install gray-matter


########################### getStaticProps ###################################
Only Allowed in a Page

getStaticProps can only be exported from a page. You can’t export it from non-page files.

One of the reasons for this restriction is that React needs to have all the required data before the page is rendered.


########################### SWR ###################################
https://swr.vercel.app/
The team behind Next.js has created a React hook for data fetching called SWR. We highly recommend it if you’re fetching data on the client side. It handles caching, revalidation, focus tracking, refetching on interval, and more. We won’t cover the details here, but here’s an example usage:


########################### Dynamic Routes ###################################


########################### Render Markdown ###################################
https://nextjs.org/learn/basics/dynamic-routes/render-markdown

npm install remark remark-html



import { remark } from 'remark';
import html from 'remark-html';



########################### Formatting the Date ###################################

https://nextjs.org/learn/basics/dynamic-routes/polishing-post-page

npm install date-fns

import { parseISO, format } from 'date-fns';

EXAMPLE:
import { parseISO, format } from 'date-fns';

export default function Date({ dateString }) {
  const date = parseISO(dateString);
  return <time dateTime={dateString}>{format(date, 'LLLL d, yyyy')}</time>;
}



    Note: You can view the different format() string options on the date-fns website.
https://date-fns.org/v2.16.1/docs/format


########################### 404 Pages ###################################
To create a custom 404 page, create pages/404.js. This file is statically generated at build time.

########################### MORE INFORMATION ###################################

https://nextjs.org/learn/basics/dynamic-routes/dynamic-routes-details


########################### API Routes ###################################
https://nextjs.org/learn/basics/api-routes/creating-api-routes
Create a file called hello.js in pages/api with the following code:
export default function handler(req, res) {
  res.status(200).json({ text: 'Hello' });
}

Try accessing it at http://localhost:3000/api/hello. You should see {"text":"Hello"}.

Do Not Fetch an API Route from getStaticProps or getStaticPaths

########################### A Good Use Case: Handling Form Input ###################################

A good use case for API Routes is handling form input. For example, you can create a form on your page and have it send a POST request to your API Route. You can then write code to directly save it to your database. The API Route code will not be part of your client bundle, so you can safely write server-side code.

export default function handler(req, res) {
  const email = req.body.email;
  // Then save email to your database, etc...
}


########################### Preview Mode ###################################
########################### Dynamic API Routes ###################################
https://nextjs.org/docs/api-routes/dynamic-api-routes

########################### VERSEL ###################################
https://vercel.com/pricing
Hobby

Free

For personal or non-commercial projects.



########################### PUBLISH and DEPLOY ###################################
https://nextjs.org/learn/basics/deploying-nextjs-app/github
https://nextjs.org/learn/basics/deploying-nextjs-app/deploy