Next.js – Static File Serving ”; Previous Next In Next.js, we can serve static pages like images very easily by putting them in public, a top level directory. We can refer these files in similar fashion like pages in pages directory. In Next.js, a page is a React Component and are exported from pages directory. Each page is associated with a route based on its file name. Let”s update the nextjs project used in Pages chapter. Create public directory and place any images within it. We”ve taken logo.png, TutorialsPoint Logo image. Update first.js as follows − import Link from ”next/link” export default function FirstPost() { return ( <> <h1>My First Post</h1> <h2> <Link href=”/”> <a>Home</a> </Link> </h2> <br/”> <img src=”/logo.png” alt=”TutorialsPoint Logo” /> </> ) } Here we”ve added a reference to logo.png in index.js file. Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000 in a browser and you will see the following output. public directory is also useful in case of SEO purpose. It can be used for robot.txt, Google Site verification or any other static assets in the web application. Print Page Previous Next Advertisements ”;
Category: nextjs
Next.js – Discussion
Discuss Next.js ”; Previous Next The Next.js is React Based framework with server side rendering capability. It is very fast and SEO friendly. Using Next.js, you can create robust react based application quite easily and test them. Print Page Previous Next Advertisements ”;
Next.js – Useful Resources
Next.js – Useful Resources ”; Previous Next The following resources contain additional information on Next.js. Please use them to get more in-depth knowledge on this topic. Useful Links on Next.js Next.js Official Site − Your main resource for Next.js documentation and examples etc. Useful Books on Next.js To enlist your site on this page, please drop an email to [email protected] Print Page Previous Next Advertisements ”;
Next.js – Typescript
Next.js – TypeScript Support ”; Previous Next Next.js, has execellent support for typescript. Following are few steps to enabling typescript in project. Create tsconfig.json Create tsconfig.json in root directory. We”re keeping it empty initially. Now start the server. Next.JS will detect tsconfig.json and show follwing message on console. npm run dev > [email protected] dev D:Nodenextjs > next ready – started server on http://localhost:3000 It looks like you”re trying to use TypeScript but do not have the required package(s) installed. Please install typescript, @types/react, and @types/node by running: npm install –save-dev typescript @types/react @types/node If you are not trying to use TypeScript, please remove the tsconfig.json file from your package root (and any TypeScript files). … Install typescript Run the npm install command to install typescript and related libraries. npm install –save-dev typescript @types/react @types/node … + @types/[email protected] + @types/[email protected] + [email protected] added 5 packages from 72 contributors and audited 839 packages in 27.538s … Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev D:Nodenextjs > next ready – started server on http://localhost:3000 We detected TypeScript in your project and created a tsconfig.json file for you. Your tsconfig.json has been populated with default values. event – compiled successfully wait – compiling… event – compiled successfully Open tsconfig.json NextJS server has modified the tsconfig.json. { “compilerOptions”: { “target”: “es5”, “lib”: [ “dom”, “dom.iterable”, “esnext” ], “allowJs”: true, “skipLibCheck”: true, “strict”: false, “forceConsistentCasingInFileNames”: true, “noEmit”: true, “esModuleInterop”: true, “module”: “esnext”, “moduleResolution”: “node”, “resolveJsonModule”: true, “isolatedModules”: true, “jsx”: “preserve” }, “exclude”: [ “node_modules” ], “include”: [ “next-env.d.ts”, “**/*.ts”, “**/*.tsx” ] } Create hello.ts Create hello.ts in pages/api directory which will acts as a rest service for us. import { NextApiRequest, NextApiResponse } from ”next” export default (_: NextApiRequest, res: NextApiResponse) => { res.status(200).json({ text: ”Welcome to TutorialsPoint” }) } Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000/api/hello in a browser and you will see the following output. {“text”:”Welcome to TutorialsPoint”} Print Page Previous Next Advertisements ”;
Next.js – Deployment
Next.js – Deployment ”; Previous Next So far we”ve developed and run sample NEXT.JS application in dev mode, now we”ll do the production ready deployment locally using following steps. npm run build − Build the production ready, highly optimized build. npm run start − Start the server. The production ready build lacks source maps and hot code reloading as compared to dev mode as those features are primarily used in debugging. Prepare Build Run the following command to prepare production ready build −. npm run build > [email protected] build Nodenextjs > next build info – Loaded env from Nodenextjs.env.local Creating an optimized production build Compiled successfully. Automatically optimizing pages Page Size First Load JS + ? / 2.25 kB 60.3 kB + /_app 288 B 58.1 kB + /404 3.25 kB 61.3 kB + ? /api/user + ? /posts/[id] 312 B 61.6 kB + + /posts/one + + /posts/two + ? /posts/env 2.71 kB 60.8 kB + ? /posts/first 374 B 61.7 kB + First Load JS shared by all 58.1 kB + static/pages/_app.js 288 B + chunks/3458401054237127135bcd3ee8eb2a19d67af299.a1a019.js 10.5 kB + chunks/framework.c6faae.js 40 kB + runtime/main.60464f.js 6.54 kB + runtime/webpack.c21266.js 746 B + css/9706b5b8ed8e82c0fba0.css 175 B ? (Server) server-side renders at runtime (uses getInitialProps or getServerSideProps) (Static) automatically rendered as static HTML (uses no initial props) ? (SSG) automatically generated as static HTML + JSON (uses getStaticProps) Start the server Run the following command to start production server −. npm run start > [email protected] start Nodenextjs > next start info – Loaded env from Nodenextjs.env.local ready – started server on http://localhost:3000 Verify Output Open localhost:3000/api/user in a browser and you will see the following output. {“name”:”Robert”} Print Page Previous Next Advertisements ”;
Next.js – Dynanic API Routes
Next.js – Dynamic Routing ”; Previous Next In Next.js, we can create routes dynamically. In this example, we”ll create pages on the fly and their routing. Step 1. Define [id].js file − [id].js represents the dynamic page where id will be relative path. Define this file in pages/post directory. Step 2. Define lib/posts.js − posts.js represents the ids and contents. lib directory is to be created in root directory. [id].js Update [id].js file with getStaticPaths() method which sets the paths and getStaticProps() method to get the contents based on id. import Link from ”next/link” import Head from ”next/head” import Container from ”../../components/container” import { getAllPostIds, getPostData } from ”../../lib/posts” export default function Post({ postData }) { return ( <Container> {postData.id} <br /> {postData.title} <br /> {postData.date} </Container> ) } export async function getStaticPaths() { const paths = getAllPostIds() return { paths, fallback: false } } export async function getStaticProps({ params }) { const postData = getPostData(params.id) return { props: { postData } } } posts.js posts.js contains getAllPostIds() to get the ids and getPostData() to get corresponding contents. export function getPostData(id) { const postOne = { title: ”One”, id: 1, date: ”7/12/2020” } const postTwo = { title: ”Two”, id: 2, date: ”7/12/2020” } if(id == ”one”){ return postOne; }else if(id == ”two”){ return postTwo; } } export function getAllPostIds() { return [{ params: { id: ”one” } }, { params: { id: ”two” } } ]; } Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000/posts/one in a browser and you will see the following output. Open localhost:3000/posts/two in a browser and you will see the following output. Print Page Previous Next Advertisements ”;
Next.js – Routing
Next.js – Routing ”; Previous Next Next.js uses file system based router. Whenever we add any page to pages directory, it is automatically available via url. Following are the rules of this router. Index Routes − An index.js file present in a folder maps to root of directory. For example − pages/index.js maps to ”/”. pages/posts/index.js maps to ”/posts”. Nested Routes − Any nested folder structure in pages directory because router url automatically. For example − pages/settings/dashboard/about.js maps to ”/settings/dashboard/about”. pages/posts/first.js maps to ”/posts/first”. Dynamic Routes − We can use named parameter as well to match url. Use brackets for the same. For example − pages/posts/[id].js maps to ”/posts/:id” where we can use URL like ”/posts/1”. pages/[user]/settings.js maps to ”/posts/:user/settings” where we can use URL like ”/abc/settings”. pages/posts/[…all].js maps to ”/posts/*” where we can use any URL like ”/posts/2020/jun/”. Page Linking Next.JS allows to link pages on client side using Link react component. It has following properties − href − name of the page in pages directory. For example /posts/first which refers to first.js present in pages/posts directory. Let”s create an example to demonstrate the same. In this example, we”ll update index.js and first.js page to make a server hit to get data. Let”s update the nextjs project used in Global CSS Support chapter. Update index.js file in pages directory as following. import Link from ”next/link” import Head from ”next/head” function HomePage(props) { return ( <> <Head> <title>Welcome to Next.js!</title> </Head> <div>Welcome to Next.js!</div> <Link href=”/posts/first”>> <a>First Post</a></Link> <br/> <div>Next stars: {props.stars}</div> <img src=”/logo.png” alt=”TutorialsPoint Logo” /> </> ) } export async function getServerSideProps(context) { const res = await fetch(”https://api.github.com/repos/vercel/next.js”) const json = await res.json() return { props: { stars: json.stargazers_count } } } export default HomePage Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000 in a browser and you will see the following output. Click on First post link. Print Page Previous Next Advertisements ”;
Next.js – CLI
Next.js – CLI ”; Previous Next NEXT.JS provides a CLI to start, build and export application. It can be invoked using npx which comes npm 5.2 onwards. CLI Help To get list of CLI commands and help on them, type the following command. npx next -h Usage $ next <command> Available commands build, start, export, dev, telemetry Options –version, -v Version number –help, -h Displays this message For more information run a command with the –help flag $ next build –help Build Production Ready Build Type the following command. npx next build info – Loaded env from D:Nodenextjs.env.local Creating an optimized production build Compiled successfully. Automatically optimizing pages Page Size First Load JS + ? / 2.25 kB 60.3 kB + /_app 288 B 58.1 kB + /404 3.25 kB 61.3 kB + ? /api/user + ? /posts/[id] 312 B 61.6 kB + + /posts/one + + /posts/two + ? /posts/env 2.71 kB 60.8 kB + ? /posts/first 374 B 61.7 kB + First Load JS shared by all 58.1 kB + static/pages/_app.js 288 B + chunks/ab55cb957ceed242a750c37a082143fb9d2f0cdf.a1a019.js 10.5 kB + chunks/framework.c6faae.js 40 kB + runtime/main.60464f.js 6.54 kB + runtime/webpack.c21266.js 746 B + css/9706b5b8ed8e82c0fba0.css 175 B ? (Server) server-side renders at runtime (uses getInitialProps or getServerSideProps) (Static) automatically rendered as static HTML (uses no initial props) ? (SSG) automatically generated as static HTML + JSON (uses getStaticProps) Build and Start Development Server Type the following command. npx next dev ready – started server on http://localhost:3000 info – Loaded env from D:Nodenextjs.env.local event – compiled successfully Start the production Server Type the following command. npx next start info – Loaded env from Nodenextjs.env.local ready – started server on http://localhost:3000 Print Page Previous Next Advertisements ”;
Next.js – Global CSS Support
Next.js – Global CSS Support ”; Previous Next In Next.js, Let”s create global styles which will be applied on all pages. In this example, we”ll create a styles.css which will be used on all components using _app.js component. Let”s update the nextjs project used in CSS Support chapter. First create a styles directory at root level and add a file styles.css as follows − html, body { padding: 0; margin: 0; line-height: 1.6; font-size: 18px; background-color: lime; } * { box-sizing: border-box; } a { color: #0070f3; text-decoration: none; } a:hover { text-decoration: underline; } img { max-width: 100%; display: block; } Create _app.js file in pages directory import ”../styles/styles.css” export default function App({ Component, pageProps }) { return <Component {…pageProps} /> } Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev Nodenextjs > next ready – started server on http://localhost:3000 event – compiled successfully event – build page: / wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000 in a browser and you will see the following output. Click on First post link. Print Page Previous Next Advertisements ”;
Next.js – API Routes
Next.js – Api Routes ”; Previous Next API Routes is a way to create rest API using Next.js. Next.js maps any file present in /pages/api folder and will be treated as API end point. An example of API function − export default (req, res) => { … } Following are some important points to consider. req − req is an instance of http.IncomingMessage and is used to get data from request. res − res is an instance of http.ServerResponse and is used to send data as response. Let”s create an example to demonstrate the same. In this example, we are going to create an user.js in pages/api directory. Let”s update the nextjs project used in Global CSS Support chapter. Create user.js file in pages/api directory as following. export default (req, res) => { res.statusCode = 200 res.setHeader(”Content-Type”, ”application/json”) res.end(JSON.stringify({ name: ”Robert” })) } Start Next.js Server Run the following command to start the server −. npm run dev > [email protected] dev D:Nodenextjs > next ready – started server on http://localhost:3000 info – Loaded env from D:Nodenextjs.env.local event – compiled successfully event – build page: /api/user wait – compiling… event – compiled successfully event – build page: /next/dist/pages/_error wait – compiling… event – compiled successfully Verify Output Open localhost:3000/api/user in a browser and you will see the following output. {“name”:”Robert”} Print Page Previous Next Advertisements ”;