tutorial

How to easily fix the “Command not found” error in VS Code

Are you developing a Visual Studio Code extension and experiencing the “Command not found” error? Let’s learn how to fix it in this article.

In this article

1. Register command in package.json contributes

To fix the “Command not found” error in a VS Code extension, make sure your extension registers the command under the contributed field in your package.json file:

package.json
{ ... "contributes": { "commands": [ ... ] } ... }

2. Register command in package.json activationEvents

To fix the “Command not found” error in a VS Code extension, make sure you’re added the command to the activationEvents array in your package.json file:

package.json
{ ... "activationEvents": [ "onCommand:extension.showMyExtension", "onCommand:extension.callMyExtension" ] ... }

3. Check console logs for any errors

One common cause of “Command not found” error in a VS Code extension is an undetected JavaScript error. You may find such errors when you examine the VS Code console logs.

Head to the Help menu and select Toggle Developer Tools and inspect the console for potential errors.

4. Register command in extension.ts registerCommand()

To fix the “Command not found” error in a VS Code extension, make sure you’re registered the command in extension.ts using vscode.commands.registerCommand():

JavaScript
// ... export async function activate(context: vscode.ExtensionContext) { // ... // commandAction is a callback function context.subscriptions.push( vscode.commands.registerCommand('command_name', commandAction) ); // ... }

5. Compile TypeScript source manually

The “Command not found” error happens in a VS Code extension if the TypeScript source wasn’t compiled to the out folder before launch or build.

This typically indicates a problem with your VS Code debug configuration, for example, preLaunchTask may be missing from launch.json:

launch.json should have a preLaunchTask which builds the VS Code extension's TypeScript files automatically.
launch.json should have a preLaunchTask which builds the TypeScript files automatically.

Or there may be a problem with the build script in package.json.

package.json
{ ... "scripts": { ... "vscode:prepublish": "npm run esbuild-base -- --minify && npm run build", "esbuild-base": "rimraf out && esbuild ./ext-src/extension.ts --bundle --outfile=out/extension.js --external:vscode --format=cjs --platform=node", "build": "webpack && tsc -p tsconfig.extension.json", ... } ... }

While you figure out what’s preventing the automatic TypeScript compilation, you can do it yourself with the tsc command:

Shell
# NPM npx tsc -p . # Yarn yarn tsc -p . # PNPM pnpm tsc -p .

6. Upgrade VS Code to match extension version

To fix the “Command not found” error in an extension, update VS Code to a version higher that what is specified in the engines.vscode field of your package.json file.

Or, downgrade engines.vscode to a version equal to or lower than the VS Code version you’re using to run the extension.

package.json
{ ... "engines": { "vscode": "^1.80.0" }, ... }

How to easily fix the EAI_AGAIN error in NPM, Yarn, or PNPM

The EAI_AGAIN error happens during an NPM, Yarn, or PNPM installation when the target server or DNS server doesn’t respond within a set time limit. This could happen due to network congestion, DNS server failures, or other connection issues.

Let’s explore some effective methods for quickly fixing the EAI_AGAIN error.

In this article

1. Clear NPM proxy

To fix the EAI_AGAIN error in NPM, Yarn, or PNPM, try removing the proxy settings from your configuration with this command:

Shell
# NPM npm config rm proxy npm config rm https-proxy # Yarn Classic (v1) yarn config delete proxy yarn config delete https-proxy # Yarn Berry (v2+) yarn config unset httpProxy yarn config unset httpsProxy # PNPM pnpm config delete proxy pnpm config delete https-proxy

2. Use faster internet connection

One simple and effective method can be to switch to a faster internet connection. Steer clear of activities that could consume additional data and leave less bandwidth for the package manager. This includes closing all unnecessary browser tabs and other data-consuming applications.

3. Retry command

Quite frequently, the EAI_AGAIN error can be temporary due to brief DNS server issues or network instability. Simply retrying the NPM/Yarn/PNPM command may solve the problem.

4. Clear package manager cache

In NPM and Yarn cache may also be a cause of the EAI_AGAIN error. Try retrying your command after clearing the cache with this command:

Shell
# NPM npm cache clean --force # Yarn yarn cache clean

5. Use different DNS server

Sometimes, the DNS server you’re using may be facing issues. Using a different DNS server like Google’s public DNS (8.8.8.8 and 8.8.4.4) or the one from Cloudflare (1.1.1.1 and 1.0.0.1) might help too.

Changing the DNS server on Windows to fix the EAI_AGAIN NPM error.
Changing the DNS server on Windows. Source: How to configure Cloudflare’s 1.1.1.1 DNS service on Windows 11, 10, or router

6. Reboot computer or server

As with many other technical issues, sometimes a simple reboot of your computer or server can fix minor problems that may contribute to the error.

7. Disable VPN or proxy

Sometimes, using a VPN or proxy at the OS level makes your package manager have connection issues. In this case, try disabling your VPN or proxy and run the NPM/Yarn/PNPM command again.

8. Connect to another network

If you’re still facing the EAI_AGAIN error, switch to a completely different network. This can help bypass potential network-specific issues causing the error.

9. Flush DNS cache

Clearing your computer’s DNS cache can also help resolve DNS-related issues that may be causing the EAI_AGAIN error. On Windows, you can do this with ipconfig /flushdns. 4 Ways to Flush the DNS Cache to Fix Web Browsing Errors.

10. Release and renew IP address

Another plausible solution to the EAI_AGAIN error can be releasing and renewing your IP address. Your IP address is what connects your computer to your network, and sometimes a bad IP configuration could possibly cause network errors.

On Windows, you can do this with ipconfig /release and ipconfig /renew. How to Reset IP Address: Mac, Windows, Linux & More.

11. Use different NPM registry

If the issue persists, try switching to a different NPM registry. For example, you can switch to the official NPM registry by running:

Shell
# NPM npm config set registry https://registry.npmjs.org/ # Yarn Classic (v1) yarn config set registry https://registry.npmjs.org/ # Yarn Berry (v2+) yarn config set npmRegistryServer https://registry.npmjs.org/ # PNPM pnpm config set registry https://registry.npmjs.org/

12. Temporarily disable antivirus or firewall

In some cases, security software like antivirus or firewall programs can interfere with network requests to NPM and cause the EAI_AGAIN error. Temporarily disable them and see if it resolves the issue.

13. Update package manager and Node.js

Make sure you are using the latest versions of Node.js and NPM, Yarn, or PNPM. You can update npm by running:

Shell
# NPM npm i -g npm@latest # Yarn npm i -g yarn@latest # PNPM npm i -g pnpm@latest

14. Try again later

Finally, if none of the above works, it may be a temporary problem with the registry server – the only thing you can do in this case is to wait for a while and then retry. Patience can sometimes be the most effective solution.

How to get the difference between two arrays in JavaScript

Get asymmetric difference between two arrays

To get the difference between two arrays in JavaScript, use the filter() and include() array methods, like this:

JavaScript
function getDifference(arrA, arrB) { return arrA.filter((element) => !arrB.includes(element)); } const arr1 = [1, 2, 3, 4]; const arr2 = [2, 4]; console.log(getDifference(arr1, arr2)); // [1, 3]

Array filter() runs a callback on every element of an array and returns an array of elements that the callback returns true for:

JavaScript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const evenNumbers = numbers.filter( (number) => number % 2 === 0 ); console.log(evenNumbers); // [2, 4, 6, 8, 10]

The Array includes() method returns true if the Array contains a particular element and returns false if it doesn’t:

JavaScript
const arr = ['a', 'b', 'c']; console.log(arr.includes('b')); // true

If we wanted to find the difference between two Sets, we’d have used Set has() in place of Array includes():

JavaScript
function getDifference(setA, setB) { return new Set( [...setA].filter(element => !setB.has(element)) ); } const set1 = new Set([1, 2, 3, 4]); const set2 = new Set([2, 4]); console.log(getDifference(set1, set2)); // {1, 3}

Get symmetric difference between two arrays

The method above only gives the methods in the second array that aren’t in the first:

JavaScript
function getDifference(arrA, arrB) { return arrA.filter((element) => !arrB.includes(element)); } const arr1 = [1, 3]; const arr2 = [1, 3, 5, 7]; console.log(getDifference(arr1, arr2)); // []

You want this sometimes, especially if arr2 is meant to be arr1‘s subset.

But other times you may want to find the symmetric difference between the arrays; regardless of which one comes first.

To do that, we simply merge the results of two getDifference() calls, each with the order of the arrays reversed:

JavaScript
function getDifference(arrA, arrB) { return arrA.filter((element) => !arrB.includes(element)); } function getSymmetricDifference(arrA, arrB) { return [ ...getDifference(arrA, arrB), ...getDifference(arrB, arrA), ]; } const arr1 = [1, 3]; const arr2 = [1, 3, 5, 7]; console.log(getSymmetricDifference(arr1, arr2)); // [5, 7] console.log(getSymmetricDifference(arr2, arr1)); // [5, 7]

How to get the difference between two sets in JavaScript

Get asymmetric difference between two sets

To get the difference between two sets in JavaScript, use the Array filter() and Set has() methods like this:

JavaScript
function getDifference(setA, setB) { return new Set( [...setA].filter(element => !setB.has(element)) ); } const set1 = new Set([1, 2, 3, 4]); const set2 = new Set([2, 4]); console.log(getDifference(set1, set2)); // {1, 3}

The Set has() method returns true if the Set contains a particular element and returns false if it doesn’t.

JavaScript
const arr = ['a', 'b', 'c']; const set = new Set(arr); console.log(set.has('a')); // true

Array filter() runs a callback on every element of an array and returns an array of elements that the callback returns true for.

JavaScript
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const evenNumbers = numbers.filter( (number) => number % 2 === 0 ); console.log(evenNumbers); // [2, 4, 6, 8, 10]

The spread syntax (...) converts the set to an array for filter() to work.

The Set() constructor converts the result of filter() back to an Set.

Get symmetric difference between two sets

The method above only gives the elements in the second set that aren’t in the first.

JavaScript
function getDifference(setA, setB) { return new Set( [...setA].filter((element) => !setB.has(element)) ); } const set1 = new Set([2, 4]); const set2 = new Set([1, 2, 3, 4]); // Every item in set1 is also in set2, but the sets are different console.log(getDifference(set1, set2)); // {}

Sometimes you want this, especially if set2 is supposed to be a set1‘s subset.

But other times you may want to find the symmetric difference between the sets, regardless of which one comes first.

To do that, we simply merge the results of two getDifference() calls, each with the order of the Sets reversed.

JavaScript
function getDifference(setA, setB) { return new Set( [...setA].filter((element) => !setB.has(element)) ); } function getSymmetricDifference(setA, setB) { return new Set([ ...getDifference(setA, setB), ...getDifference(setB, setA), ]); } const set1 = new Set([2, 4]); const set2 = new Set([1, 2, 3, 4]); console.log(getSymmetricDifference(set1, set2)); // {1, 3} console.log(getSymmetricDifference(set2, set1)); // {1, 3}

How to easily detect when the mouse leaves the browser window in JavaScript

Detecting when the mouse leaves the browser window helps to track user engagement and display custom messages or popups.

Let’s learn how to do it with JavaScript.

Detect browser window mouse exit

To detect when the mouse leaves the browser window, use the mouseleave event listener:

index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> <link rel="icon" href="favicon.ico" /> </head> <body> <div id="notifier"></div> <button class="btn-1">Be amazing</button> <script src="index.js" /> </body> </html>
index.js
document.addEventListener('mouseleave', () => { document.querySelector('#notifier').textContent = "Don't leave me!"; });

The mouseleave event fires on an Element when the mouse exits its bounds.

You can also use document.body to listen for when the user exits the window, but the body needs to be as big as the viewport for this to work:

index.js
document.addEventListener('mouseleave', () => { document.querySelector('#notifier').textContent = "Don't leave me!"; });
index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> <link rel="icon" href="favicon.ico" /> <style> /* Makes body as big as viewport */ html, body { margin: 0; height: 100%; width: 100%; } </style> </head> <body> <h2>Welcome fellow developer</h2> <div id="notifier"></div> <script src="index.js"></script> </body> </html>

Using document.body over document could be better for compatibility with later Firefox versions.

Detect when user about to exit webpage

This helps to display an exit-intent popup, usually shown when the user is about to close the webpage or go to another.

Since tabs are usually at the top of the browser, we’d detect when the mouse leaves the browser window, but only from the top:

index.js
document.addEventListener('mouseleave', (event) => { if (event.clientY <= 0) { document.querySelector('#notifier').textContent = 'Have a good day!'; } });

clientY will be 0 at the very top of the viewport, so any higher and our if block’s code runs.

index.html
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> <link rel="icon" href="favicon.ico" /> </head> <body> <h2 id="notifier"></h2> <div> Welcome to Coding Beauty, a site for all things coding. </div> <script src="index.js" /> </body> </html>

How to easily fix the “Cannot read property ‘classList’ of null” error in JavaScript

The “Cannot read property ‘classList’ of null” error happens in JavaScript when you try to access the classList property on an element that isn’t in the HTML DOM.

Let’s look at various ways to quickly fix this error.

Fix: Ensure correct selector

To fix the “Cannot read property ‘classList’ of null” error in JavaScript, ensure the correct selector accesses an existing HTML element.

HTML
<div>Welcome to Coding Beauty</div> <button class="btn-1">Be amazing</button>

Check for any mistakes in the selector symbols in the script. Check for any mistakes in the ID or class name in the HTML tag. Maybe you forgot to set that id or class attribute at all?

JavaScript
// forgot the '.' symbol used for class selectors const button = document.querySelector('btn-1'); console.log(button); // 👉️ undefined // ❌ Uncaught TypeError: Cannot read properties of undefined (reading 'classList') button.classList.add('active');

Fix: Ensure DOM load before .classList access

The “Cannot read property ‘classList’ of undefined” error also occurs when you try to access .classList on an element that the browser hasn’t added to the DOM yet.

Maybe because your <script> is in the <head> tag and executes before the element’s parsing:

HTML
<!DOCTYPE html> <html lang="en"> <head> <title>Coding Beauty Tutorial</title> <!-- ❌ Script is run before button is declared --> <script src="index.js"></script> </head> <body> <div id="element"> console.log('Easy answers to your coding questions and more...'); </div> </body> </html>

The script tag is placed in the <head> tag above where the div is declared, so index.js can’t access the div.

index.js
const element = document.querySelector('.element'); console.log(element); // 👉️ undefined // ❌ Uncaught TypeError: Cannot read properties of undefined (reading 'classList') element.classList.add('highlight');

Solution: Move script to bottom

To fix the error in this case, move the script tag to the bottom of the body, after all the HTML elements have been declared.

HTML
<!DOCTYPE html> <html lang="en"> <head> <title>Coding Beauty Tutorial</title> </head> <body> <div id="element"> console.log('Easy answers to your coding questions and more...'); </div> <!-- ❌ Script is run after element is added to the DOM --> <script src="index.js"></script> </body> </html>

Now index.js will have access to the div and all the other HTML elements, because the browser would have rendered them by the time the script runs:

index.js
const element = document.querySelector('.element'); console.log(element); // 👉️ undefined // ✅ Works as expected element.classList.add('highlight');

Solution: Access .classList in DOMContentLoaded event listener

Another way to fix the “cannot read property ‘addEventListener’ of null” error is to add a DOMContentLoaded event listener to the document and access the element in this listener.

HTML
<!DOCTYPE html> <html lang="en"> <head> <title>Coding Beauty Tutorial</title> <!-- Script placed above accessed element --> <script src="index.js"></script> </head> <body> <div id="element"> console.log('Coding is more than a means to an end...'); </div> </body> </html>

The DOMContentLoaded event fires when the browser fully parses the HTML, whether or not external resources like images and stylesheets have loaded.

So regardless of where we place the script, the code in the listener only runs after every element is active in the DOM.

index.js
const element = document.querySelector('.element'); console.log(element); // 👉️ undefined // ✅ Works as expected element.classList.add('highlight');

How to easily add a favicon to a Next.js app

Adding a favicon to a website enhances usability and branding. It helps identify the website in browser tabs and bookmarks, improving user recognition and trust.

Let’s learn how to quickly add a favicon image to a Next.js app

In this article

Add favicon automatically in Next.js 13 App Router

To add a favicon in Next.js 13 App Router, add a favicon.ico file to the app/ directory. Next.js will automatically detect favicon.ico and display it on the page.

Here we’ve added the favicon.ico to our VS Code Next.js project.

favicon.ico is the app directory in Visual Studio Code.

And this is all we need to do – here’s layout.tsx:

src/app/layout.tsx
import { Metadata } from 'next'; import './globals.css'; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body>{children}</body> </html> ); }

And we’ll instantly see the image next to the page title in the browser tab:

The favicon shows up next to the page title in the browser-tab

Apart from favicon and .ico, Next.js also auto-discovers the following file name and extension combinations in the app/ directory

  • icon with .ico, .jpg, .jpeg, .png, or.svg extension.
  • app-icon with .jpg, .jpeg, .png extension.

You can rename PNGs to .ico files and they will still work.

Add favicon automatically in Next.js Pages Router

To add a favicon automatically in the Next.js pages directory, place a favicon.ico file in your public/ directory, and your browser will automatically detect the file for the site icon.

favicon.ico is the public directory in Visual Studio Code.

If your image file isn’t a .ico, you’ll need to either rename it to favicon.ico, or manually specify the filename.

Set Next.js favicon statically in Next.js 13 App Router

To add a favicon to a Next.js 13 app, you can also export a Metadata object with an icons property in your layout.tsx file:

src/app/layout.tsx
import { Metadata } from 'next'; import './globals.css'; export const metadata: Metadata = { icons: { icon: '/icon.png', }, }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body>{children}</body> </html> ); }

The image file should be in your public directory.

Set Next.js favicon with HTML in Pages Router

To add a site icon in the Next.js pages or app directory, use the HTML <link> tag in your _document.tsx or _document.js file, just like in vanilla HTML:

pages/_document.tsx
import { Html, Head, Main, NextScript } from 'next/document'; export default function Document() { return ( <Html lang="en"> <Head> <link rel="icon" href="/favicon.png" /> </Head> <body> <Main /> <NextScript /> </body> </Html> ); }

The favicon should be in your public directory.

Add favicon with HTML in Next.js 13 App Router

You can also use the HTML <link> tag to add a favicon in a project using the Next.js app directory, in your layout.tsx file:

src/app/layout.tsx
import './globals.css'; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <head> <link rel="icon" href="/app-icon.jpg" /> </head> <body>{children}</body> </html> ); }

The favicon should be in your public directory.

How to add or toggle a class on the body element in JavaScript

Adding a class to the <body> tag can be useful for applying global styles or targeting specific elements within the body for styling or functionality.

This article will teach us how to easily add or toggle a class on the HTML body element using JavaScript.

In this article

To add a class to the HTML body element in JavaScript on page load, call the classList.add() method on it, i.e., document.body.classList.add(element).

HTML
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> </head> <body class="dev coding"> <div>This is a div element.</div> </body> </html>
JavaScript
document.body.classList.add('class-3');

The body property is the HTMLElement object that represents the body tag in the markup.

The classList property is a DOMTokenList object that represents the list of classes an element has.

The add() method of the classList property takes a list of classes and adds them to an element.

JavaScript
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> </head> <body class="dev coding beauty"> <div>This is a div element.</div> </body> </html>

You can pass multiple arguments to add() to add more than one class to the body. For example, we can add both beauty and magic to the body in single statement.

JavaScript
document.body.classList.add('beauty', 'magic');

To produce this HTML markup:

JavaScript
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> </head> <body class="dev coding beauty magic"> <div>This is a div element.</div> </body> </html>

If you add class that already exists on the HTML body, add() ignores the class instead of throwing an exception.

Add class to body tag in <head> tag

To add a class to the body element in the <head> tag using JavaScript, use the DOMContentLoaded event and the document.body.classList.add() method.

For example:

JavaScript
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> <script> document.addEventListener('DOMContentLoaded', () => { document.body.classList.add('beauty', 'magic'); }); </script> </head> <body class="dev coding"> <div>This is a div element.</div> <script src="index"></script> </body> </html>

The DOMContentLoaded event runs when the HTML is completely parse and the DOM has loaded.

The <script> loads and the JavaScript runs before the browser renders the HTML, so without DOMContentLoaded, document.body will be null in the <script>, causing the “Cannot read property ‘classList’ of undefined” JavaScript error.

The "Cannot read property 'classList' of undefined" error happening in JavaScript.

Add class to body tag on click

If you’d like to add a class to the body tag when the user clicks an element, set a click listener on element and call document.body.classList.add() in this listener.

For example:

HTML
<!DOCTYPE html> <html> <head> <title>Coding Beauty Tutorial</title> </head> <body class="dev coding"> <div>So you can code</div> <button class="amazify">Be amazing</button> </body> </html>
JavaScript
const button = document.getElementById('amazify'); button.addEventListener('click', () => { document.body.classList.add('amazify'); });

Toggle class on body element

Toggling a class on the body element in JavaScript simplifies code implementation by handling the addition and removal of the class in a single line of code.

And this single line of code is a call to the body’s classList.toggle() method:

JavaScript
document.body.classList.toggle('incredible');

As you would expect, the class is removed from the body when it’s already there and added when it isn’t.

Next.js: How to set page title and meta description

Setting the page title and meta description helps improve search engine visibility, increase click-through rates, and provide concise summaries of webpage content.

In this article, we’re going to learn how we easily set the page title and meta description in a Next.js project.

In this article

Set static page title and meta description in Next.js App Router

To set page title and meta description statically in Next.js 13’s app directory, create a Metadata object in a page.tsx file and export it:

src/app/page.tsx
import React from 'react'; import { Metadata } from 'next'; export const metadata: Metadata = { title: 'Coding Beauty', description: 'codingbeautydev.com: Coding - the art, the science, and the passion.', }; export default function Page() { return ( <main> <h1>Welcome to Coding Beauty</h1> </main> ); }

The tab will have this title, and the page will have a meta tag containing this description:

A Next.js page with a title and meta description.

We can also do this in a layout.tsx to make every page using this layout have this title and meta description by default – if the page doesn’t have its own.

src/app/layout.tsx
import { Metadata } from 'next'; import '@/styles/globals.css'; export const metadata: Metadata = { title: 'Coding Beauty', description: 'The official Coding Beauty home page.', icons: { icon: '/favicon.png', }, }; export default function RootLayout({ children, }: { children: React.ReactNode; }) { return ( <html lang="en"> <body>{children}</body> </html> ); }

Set title and meta description dynamically in Next.js App Router

You can use the generateMetadata() function to set the page title and meta description using dynamic information we don’t know beforehand, like data from an API.

TypeScript
export function generateMetadata({ params }: Props): Promise<Metadata> { // fetch data with `params` // return a `Metadata` object return { title: post.name, description: post.description, } }

Let’s look at a full example, where we fetch API data for a post in our hypothetical social media app, and we use generateMetadata() to set the page title and meta description for the page based on what we get from the endpoint URL.

src/pages/posts/[id]/page.tsx
import { Metadata } from 'next'; type Props = { params: { id: string }; }; export async function generateMetadata({ params, }: Props): Promise<Metadata> { const id = params.id; const url = `https://api.mysocialapp.com/posts/${id}`; const post = await fetch(url).then((res) => res.json()); return { title: post.title, description: post.description, }; } export default async function Page({ params }: Props) { const { id } = params; const url = `https://api.mysocialapp.com/posts/${id}`; // fetch again! // But don't worry, Next.js caches the `fetch()` calls const post = await fetch(url).then((res) => res.json()); return ( <> <h1>{post.title}</h1> <div>{post.content}</div> </> ); }

We fetch data from the same endpoint twice, one for the title and meta description, and another to display the title and other information to the actual users on the page.

Next.js caches the results of the fetch in generateMetadata() for use in Page to prevent multiple requests and avoid performance hits.

If you export a Metadata object and also have generateMetadata() function, Next.js will use generateMetadata()‘s return value.

Set page title and meta description in Next.js Pages Router (<= 12)

To set the page title and meta description in the Next.js pages directory, create a Head component, and place meta and title tags in it, like you would in vanilla HTML:

pages/index.tsx
import Head from 'next/head'; export default function Home() { return ( <> <Head> <title>Coding Beauty</title> <meta name="description" content="A brand all about coding passion and success" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.png" /> </Head> <main> <h1>Welcome to Coding Beauty</h1> </main> </> ); }

We can also set the page title and meta description in your _app.tsx or _app.jsx file to make each page without a title or description use this as a default.

pages/_app.tsx
import '@/styles/globals.css'; import type { AppProps } from 'next/app'; import Head from 'next/head'; export default function App({ Component, pageProps }: AppProps) { return ( <> <Head> <title>Coding Beauty</title> <meta name="description" content="A page on the Coding Beauty website" /> </Head> <Component {...pageProps} /> </> ); }

Set page title and meta description dynamically in Next.js Pages Router (<= 12)

You can also set the page title and meta description in the pages directory based on some data not known ahead of time.

For instance, to set the meta information based on API data, you’ll fetch the data in getServerSideProps and display it in the title and meta tags that are in the Head tag.

pages/[id].tsx
import { GetServerSideProps } from 'next'; import Head from 'next/head'; export const getServerSideProps: GetServerSideProps = async (context) => { const { params } = context; const { id } = params!; const result = await fetch(`api.mystore.com/books/${id}`); const { title, description, details } = await result.json(); return { props: { title, description, details, }, }; }; export default function Home(props: any) { const { title, description, details } = props; return ( <> <Head> {/* 👇 set page title and meta description dynamically */} <title>{title}</title> <meta name="description" content={description} /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="/favicon.png" /> </Head> <main> <h1>{title}</h1> <p>{details}</p> </main> </> ); }

How to create a type from type or object keys or values in TypeScript

In this article

Create type from object keys in TypeScript

To create a type from an object’s keys in TypeScript, use the keyof typeof object. For example:

TypeScript
const brand = { name: 'Coding Beauty', domain: 'codingbeautydev.com', color: 'blue', }; // 👇 type Keys = 'name' | 'domain' | 'color'; type BrandKeys = keyof typeof brand;

With this, you’ll have a type that only accepts strings matching the key name, and your code editor’s intellisense should indicate:

The new type only accepts values matching the object's keys.
The new type only accepts values matching the object’s keys.

Create type from another type’s keys in TypeScript

We use typeof because brand is an instance object, not a type. If it was a type, we would omit typeof:

TypeScript
type Brand = { name: string; domain: string; color: string; }; // 👇 type Keys = 'name' | 'domain' | 'color'; type BrandKeys = keyof Brand;

As before, you’ll have a type that only contains strings matching the key name, and your code editor should detect this:

The new type only accepts values matching the first type's keys.
The new type only accepts values matching the first type’s keys.

Create type from object values in TypeScript

We can use typeof and type indexing to easily create a type from an object’s values in TypeScript:

TypeScript
const site = { url: 'codingbeautydev.com', color: 'blue', topic: 'coding', } as const; // 👈 const assertion // 👇 type Values = 'codingbeautydev.com' | 'color' | 'coding' type Values = (typeof site)[keyof typeof site];

We this, we’ll have a type that only accepts strings matching the values of the object:

The new type only accepts values matching the object's values.
The new type only accepts values matching the object’s values.

Otherwise, there’ll be a TypeScript error

You can only values matching the object's values to the new type.

Create generic type from object values in TypeScript

The as const is called a const assertion in TypeScript. It tells the compiler to infer the most specific type possible from an expression. Without it, the inferred value type will be a primitive, like string or number or union of these primitives – string | number for example.

TypeScript
const site = { url: 'codingbeautydev.com', color: 'blue', topic: 'coding', }; // 👇 type Values = 'string' type Values = (typeof site)[keyof typeof site]; // 👇 No error - `Values` takes any string const testObj: Values = 'random string';

Values is no different from the string type here, and VS Code confirms it:

The Values type is a string.
The Values type is a string.

If there are multiple primitive types, the resulting generic type will be a union of all those primitives:

TypeScript
const site = { url: 'codingbeautydev.com', age: 1000, // 👈 also `number` type now topic: 'coding', }; // 👇 type Values = 'string' | number type Values = (typeof site)[keyof typeof site]; // 👇 No error const testObj: Values = 34124;
The Values type is a string | number type.
The Values type is a string | number type.

Create generic type from another type’s values in TypeScript

You can also create generic types from another type’s values in TypeScript, like this:

TypeScript
type Site = { url: 'codingbeautydev.com'; age: number; topic: string; }; // 👇 type Site = 'string' | 'number' type Values = Site[keyof Site];
The Values type comes from the Site type's values.
The Values type comes from the Site type’s values.