Unverified Commit a973ad64 authored by Michael Novotny's avatar Michael Novotny Committed by GitHub

Makes codeblock language and filename extensions consistent (#51056)

There was mismatched usage of `js`, `jsx`, `ts`, and `tsx`. Just tried to get them all in sync.
parent 98351e93
......@@ -41,10 +41,12 @@ Failed to load SWC binary, see more info here: https://nextjs.org/docs/messages/
Try to add the below section to your `package.json`, then run again
```json
"optionalDependencies": {
"@next/swc-linux-x64-gnu": "canary",
"@next/swc-win32-x64-msvc": "canary",
"@next/swc-darwin-x64": "canary",
"@next/swc-darwin-arm64": "canary"
},
{
"optionalDependencies": {
"@next/swc-linux-x64-gnu": "canary",
"@next/swc-win32-x64-msvc": "canary",
"@next/swc-darwin-x64": "canary",
"@next/swc-darwin-arm64": "canary"
}
}
```
......@@ -70,7 +70,7 @@ export default function Counter() {
}
```
```jsx filename="app/counter.jsx" highlight={1} switcher
```jsx filename="app/counter.js" highlight={1} switcher
'use client'
import { useState } from 'react'
......
......@@ -42,7 +42,7 @@ There are optional props you can pass to `<Link>`. See the [API reference](/docs
When linking to [dynamic segments](/docs/app/building-your-application/routing/dynamic-routes), you can use [template literals and interpolation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) to generate a list of links. For example, to generate a list of blog posts:
```jsx filename="app/blog/PostList.jsx"
```jsx filename="app/blog/PostList.js"
import Link from 'next/link'
export default function PostList({ posts }) {
......@@ -62,7 +62,7 @@ export default function PostList({ posts }) {
You can use [`usePathname()`](/docs/app/api-reference/functions/use-pathname) to determine if a link is active. For example, to add a class to the active link, you can check if the current `pathname` matches the `href` of the link:
```jsx filename="app/ui/Navigation.jsx"
```jsx filename="app/ui/Navigation.js"
'use client'
import { usePathname } from 'next/navigation'
......@@ -109,7 +109,7 @@ The `useRouter` hook allows you to programmatically change routes inside [Client
To use `useRouter`, import it from `next/navigation`, and call the hook inside your Client Component:
```jsx filename="app/page.jsx"
```jsx filename="app/page.js"
'use client'
import { useRouter } from 'next/navigation'
......
......@@ -21,9 +21,15 @@ Dynamic Segments are passed as the `params` prop to [`layout`](/docs/app/api-ref
For example, a blog could include the following route `app/blog/[slug]/page.js` where `[slug]` is the Dynamic Segment for blog posts.
```tsx filename="app/blog/[slug]/page.js"
```tsx filename="app/blog/[slug]/page.tsx" switcher
export default function Page({ params: { slug: string } }) {
return <div>My Post: {slug}</div>
}
```
```jsx filename="app/blog/[slug]/page.js" switcher
export default function Page({ params }) {
return <div>My Post</div>
return <div>My Post: {slug}</div>
}
```
......
......@@ -126,6 +126,7 @@ Both [`useSelectedLayoutSegment`](/docs/app/api-reference/functions/use-selected
```tsx filename="app/layout.tsx" switcher
'use client'
import { useSelectedLayoutSegment } from 'next/navigation'
export default async function Layout(props: {
......@@ -139,6 +140,7 @@ export default async function Layout(props: {
```jsx filename="app/layout.js" switcher
'use client'
import { useSelectedLayoutSegment } from 'next/navigation'
export default async function Layout(props) {
......@@ -251,7 +253,7 @@ export default async function Login() {
}
```
```jsx filename="app/@authModal/login/page.jsx" highlight="5" switcher
```jsx filename="app/@authModal/login/page.js" highlight="5" switcher
'use client'
import { useRouter } from 'next/navigation'
import { Modal } from 'components/modal'
......@@ -280,7 +282,13 @@ If you want to navigate elsewhere and dismiss a modal, you can also use a catch-
height="768"
/>
```tsx filename="app/@authModal/[...catchAll]/page.js"
```tsx filename="app/@authModal/[...catchAll]/page.tsx" switcher
export default function CatchAll() {
return null
}
```
```jsx filename="app/@authModal/[...catchAll]/page.js" switcher
export default function CatchAll() {
return null
}
......
......@@ -187,7 +187,7 @@ You can consider a `route` the lowest level routing primitive.
Each `route.js` or `page.js` file takes over all HTTP verbs for that route.
```tsx filename="app/page.js"
```jsx filename="app/page.js"
export default function Page() {
return <h1>Hello, Next.js!</h1>
}
......
......@@ -127,7 +127,7 @@ Next.js supports storing application code (including `app`) inside an optional [
Next.js supports [Module Path Aliases](/docs/app/building-your-application/configuring/absolute-imports-and-module-aliases) which make it easier to read and maintain imports across deeply nested project files.
```tsx filename="app/dashboard/settings/analytics/page.js"
```jsx filename="app/dashboard/settings/analytics/page.js"
// before
import { Button } from '../../../components/button'
......
......@@ -18,7 +18,7 @@ It’s recommended to use the user’s language preferences in the browser to se
For example, using the following libraries, you can look at an incoming `Request` to determine which locale to select, based on the `Headers`, locales you plan to support, and the default locale.
```jsx filename="middleware.js"
```js filename="middleware.js"
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
......@@ -32,7 +32,7 @@ match(languages, locales, defaultLocale) // -> 'en-US'
Routing can be internationalized by either the sub-path (`/fr/products`) or domain (`my-site.fr/products`). With this information, you can now redirect the user based on the locale inside [Middleware](/docs/app/building-your-application/routing/middleware).
```jsx filename="middleware.js"
```js filename="middleware.js"
import { NextResponse } from 'next/server'
let locales = ['en-US', 'nl-NL', 'nl']
......@@ -87,7 +87,7 @@ Changing displayed content based on the user’s preferred locale, or localizati
Let’s assume we want to support both English and Dutch content inside our application. We might maintain two different “dictionaries”, which are objects that give us a mapping from some key to a localized string. For example:
```jsx filename="dictionaries/en.json"
```json filename="dictionaries/en.json"
{
"products": {
"cart": "Add to Cart"
......@@ -95,7 +95,7 @@ Let’s assume we want to support both English and Dutch content inside our appl
}
```
```jsx filename="dictionaries/nl.json"
```json filename="dictionaries/nl.json"
{
"products": {
"cart": "Toevoegen aan Winkelwagen"
......
......@@ -368,7 +368,7 @@ If the segment is static (default), the output of the request will be cached and
As a temporary solution, until the caching behavior of third-party queries can be configured, you can use [segment configuration](/docs/app/api-reference/file-conventions/route-segment-config#revalidate) to customize the cache behavior of the entire segment.
```ts filename="app/page.tsx" switcher
```tsx filename="app/page.tsx" switcher
import prisma from './lib/prisma'
export const revalidate = 3600 // revalidate every hour
......
......@@ -76,7 +76,7 @@ export default async function Page() {
React allows you to [`cache()`](https://github.com/acdlite/rfcs/blob/first-class-promises/text/0000-first-class-support-for-promises.md) and deduplicate requests, memoizing the result of the wrapped function call. The same function called with the same arguments will reuse a cached value instead of re-running the function.
```tsx filename="utils/getUser.ts" switcher
```ts filename="utils/getUser.ts" switcher
import { cache } from 'react'
export const getUser = cache(async (id: string) => {
......@@ -85,7 +85,7 @@ export const getUser = cache(async (id: string) => {
})
```
```jsx filename="utils/getUser.js" switcher
```js filename="utils/getUser.js" switcher
import { cache } from 'react'
export const getUser = cache(async (id) => {
......@@ -146,7 +146,7 @@ Although the `getUser()` function is called twice in the example above, only one
`POST` requests are automatically deduplicated when using `fetch` – unless they are inside of `POST` Route Handler or come after reading `headers()`/`cookies()`. For example, if you are using GraphQL and `POST` requests in the above cases, you can use `cache` to deduplicate requests. The `cache` arguments must be flat and only include primitives. Deep objects won't match for deduplication.
```tsx filename="utils/getUser.ts" switcher
```ts filename="utils/getUser.ts" switcher
import { cache } from 'react'
export const getUser = cache(async (id: string) => {
......@@ -155,7 +155,7 @@ export const getUser = cache(async (id: string) => {
})
```
```jsx filename="utils/getUser.js" switcher
```js filename="utils/getUser.js" switcher
import { cache } from 'react'
export const getUser = cache(async (id) => {
......@@ -232,7 +232,7 @@ export default async function Page({ params: { id } }) {
You can combine the `cache` function, the `preload` pattern, and the `server-only` package to create a data fetching utility that can be used throughout your app.
```tsx filename="utils/getUser.ts" switcher
```ts filename="utils/getUser.ts" switcher
import { cache } from 'react'
import 'server-only'
......@@ -245,7 +245,7 @@ export const getUser = cache(async (id: string) => {
})
```
```jsx filename="utils/getUser.js" switcher
```js filename="utils/getUser.js" switcher
import { cache } from 'react'
import 'server-only'
......
......@@ -15,7 +15,7 @@ There are two types of revalidation in Next.js:
To revalidate cached data at a specific interval, you can use the `next.revalidate` option in `fetch()` to set the `cache` lifetime of a resource (in seconds).
```jsx
```js
fetch('https://...', { next: { revalidate: 60 } })
```
......@@ -76,7 +76,7 @@ export default async function Page() {
This cached data can then be revalidated on-demand by calling `revalidateTag` in a [Route Handler](/docs/app/building-your-application/routing/router-handlers).
```tsx filename="app/api/revalidate/route.ts" switcher
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
......@@ -87,7 +87,7 @@ export async function GET(request: NextRequest) {
}
```
```jsx filename="app/api/revalidate/route.js" switcher
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
......
......@@ -13,7 +13,7 @@ related:
**With Server Components:**
```jsx filename="app/add-to-cart.jsx" highlight={5, 6, 13}
```jsx filename="app/add-to-cart.js" highlight={5, 6, 13}
import { cookies } from 'next/headers'
// Server action defined inside a Server Component
......@@ -44,7 +44,7 @@ async function addItem(data) {
}
```
```jsx filename="app/add-to-cart.jsx" highlight={1, 3, 8}
```jsx filename="app/add-to-cart.js" highlight={1, 3, 8}
'use client'
import { addItem } from './actions.js'
......@@ -88,7 +88,7 @@ Server Actions can be defined in two places:
Create a Server Action by defining an asynchronous function with the `"use server"` directive at the top of the function body. This function should have **serializable arguments** and a **serializable return value** based on the React Server Components protocol.
```jsx filename="app/server-component.jsx" highlight={2}
```jsx filename="app/server-component.js" highlight={2}
export default function ServerComponent() {
async function myAction() {
'use server'
......@@ -101,7 +101,7 @@ export default function ServerComponent() {
If you're using a Server Action inside a Client Component, create your action in a separate file with the "use server" directive at the top of the file. Then, import the Server Action into your Client Component:
```jsx filename="app/actions.js" highlight={1}
```js filename="app/actions.js" highlight={1}
'use server'
export async function myAction() {
......@@ -109,7 +109,7 @@ export async function myAction() {
}
```
```jsx filename="app/client-component.jsx" highlight={1}
```jsx filename="app/client-component.js" highlight={1}
'use client'
import { myAction } from './actions'
......@@ -160,7 +160,7 @@ export default function AddToCart({ productId }) {
You can use `formAction` prop to handle **Form Actions** on elements such as `button`, `input type="submit"`, and `input type="image"`. The `formAction` prop takes presedence over the form's `action`.
```jsx filename="app/form" highlight={15}
```jsx filename="app/form.js" highlight={15}
export default function Form() {
async function handleSubmit() {
'use server'
......@@ -207,7 +207,7 @@ function ExampleClientComponent({ id }) {
}
```
```jsx filename="app/actions.js"
```js filename="app/actions.js"
'use server'
export async function addItem(id) {
......@@ -390,7 +390,7 @@ In both cases, the form is interactive before hydration occurs. Although Server
Server Actions **cannot** be _defined_ within Client Components, but they can be _imported_. To use Server Actions in Client Components, you can import the action from a file containing a top-level `"use server"` directive.
```jsx filename="app/actions.js" highlight={1}
```js filename="app/actions.js" highlight={1}
'use server'
export async function addItem() {
......@@ -455,7 +455,7 @@ function ExampleClientComponent({ updateItem }) {
Server Actions can be used to revalidate data on-demand by path ([`revalidatePath`](/docs/app/api-reference/functions/revalidatePath)) or by cache tag ([`revalidateTag`](/docs/app/api-reference/functions/revalidateTag)).
```jsx
```js
import { revalidateTag } from 'next/cache'
async function revalidate() {
......@@ -468,7 +468,7 @@ async function revalidate() {
The data passed to a Server Action can be validated or sanitized before invoking the action. For example, you can create a wrapper function that receives the action as its argument, and returns a function that invokes the action if it's valid.
```jsx filename="app/actions.js"
```js filename="app/actions.js"
'use server'
import { withValidate } from 'lib/form-validation'
......@@ -478,7 +478,7 @@ export const action = withValidate((data) => {
})
```
```jsx filename="lib/form-validation"
```js filename="lib/form-validation.js"
export function withValidate(action) {
return (formData: FormData) => {
'use server'
......@@ -499,7 +499,7 @@ export function withValidate(action) {
You can read incoming request headers such as `cookies` and `headers` within a Server Action.
```jsx highlight={6}
```js highlight={6}
import { cookies } from 'next/headers'
async function addItem(data) {
......@@ -513,7 +513,7 @@ async function addItem(data) {
Additionally, you can modify cookies within a Server Action.
```jsx highlight={7, 9, 10, 11, 12, 13, 14}
```js highlight={7, 9, 10, 11, 12, 13, 14}
import { cookies } from 'next/headers';
async function create(data) {
......
......@@ -249,7 +249,7 @@ export default function MyApp({ Component, pageProps }) {
For importing CSS required by a third-party component, you can do so in your component. For example:
```tsx filename="components/example-dialog.js"
```jsx filename="components/example-dialog.js"
import { useState } from 'react'
import { Dialog } from '@reach/dialog'
import VisuallyHidden from '@reach/visually-hidden'
......
......@@ -29,7 +29,7 @@ The Next.js Image component extends the HTML `<img>` element with features for a
## Usage
```jsx
```js
import Image from 'next/image'
```
......
......@@ -241,7 +241,7 @@ You can import and use multiple fonts in your application. There are two approac
The first approach is to create a utility function that exports a font, imports it, and applies its `className` where needed. This ensures the font is preloaded only when it's rendered:
```tsx filename="app/fonts.ts" switcher
```ts filename="app/fonts.ts" switcher
import { Inter, Roboto_Mono } from 'next/font/google'
export const inter = Inter({
......@@ -255,7 +255,7 @@ export const roboto_mono = Roboto_Mono({
})
```
```jsx filename="app/fonts.js" switcher
```js filename="app/fonts.js" switcher
import { Inter, Roboto_Mono } from 'next/font/google'
export const inter = Inter({
......@@ -568,7 +568,7 @@ export default function RootLayout({ children }) {
<PagesOnly>
```js filename="pages/_app.js"
```jsx filename="pages/_app.js"
import { Inter } from 'next/font/google'
const inter = Inter({
......
......@@ -91,7 +91,7 @@ export default function RootLayout({ children }) {
To load a third-party script for all routes, import `next/script` and include the script directly in your custom `_app`:
```jsx filename="pages/_app.js
```jsx filename="pages/_app.js"
import Script from 'next/script'
export default function MyApp({ Component, pageProps }) {
......
......@@ -156,7 +156,7 @@ This means metadata with nested fields such as [`openGraph`](/docs/app/api-refer
#### Overwriting fields
```tsx filename="app/layout.js"
```jsx filename="app/layout.js"
export const metadata = {
title: 'Acme',
openGraph: {
......@@ -166,7 +166,7 @@ export const metadata = {
}
```
```tsx filename="app/blog/page.js"
```jsx filename="app/blog/page.js"
export const metadata = {
title: 'Blog',
openGraph: {
......@@ -186,11 +186,11 @@ In the example above:
If you'd like to share some nested fields between segments while overwriting others, you can pull them out into a separate variable:
```tsx filename="app/shared-metadata.js"
```jsx filename="app/shared-metadata.js"
export const openGraphImage = { images: ['http://...'] }
```
```tsx filename="app/page.js"
```jsx filename="app/page.js"
import { openGraphImage } from './shared-metadata'
export const metadata = {
......@@ -201,7 +201,7 @@ export const metadata = {
}
```
```tsx filename="app/about/page.js"
```jsx filename="app/about/page.js"
import { openGraphImage } from '../shared-metadata'
export const metadata = {
......@@ -216,7 +216,7 @@ In the example above, the OG image is shared between `app/layout.js` and `app/ab
#### Inheriting fields
```tsx filename="app/layout.js"
```jsx filename="app/layout.js"
export const metadata = {
title: 'Acme',
openGraph: {
......@@ -226,7 +226,7 @@ export const metadata = {
}
```
```tsx filename="app/about/page.js"
```jsx filename="app/about/page.js"
export const metadata = {
title: 'About',
}
......@@ -250,7 +250,7 @@ The `ImageResponse` constructor allows you to generate dynamic images using JSX
To use it, you can import `ImageResponse` from `next/server`:
```jsx filename="app/about/route.jsx"
```jsx filename="app/about/route.js"
import { ImageResponse } from 'next/server'
export const runtime = 'edge'
......
......@@ -16,7 +16,7 @@ The rest of this documentation describes the built-in relayer Next.js Speed Insi
First, you will need to create a [custom App](/docs/pages/building-your-application/routing/custom-app) component and define a `reportWebVitals` function:
```js filename="pages/_app.js"
```jsx filename="pages/_app.js"
export function reportWebVitals(metric) {
console.log(metric)
}
......@@ -203,7 +203,7 @@ export function reportWebVitals(metric: NextWebVitalsMetric) {
export default MyApp
```
```js filename="pages/_app.js" switcher
```jsx filename="pages/_app.js" switcher
function MyApp({ Component, pageProps }) {
return <Component {...pageProps} />
}
......
......@@ -6,8 +6,10 @@ description: Next.js provides an integrated ESLint experience by default. These
Next.js provides an integrated [ESLint](https://eslint.org/) experience out of the box. Add `next lint` as a script to `package.json`:
```json filename="package.json"
"scripts": {
"lint": "next lint"
{
"scripts": {
"lint": "next lint"
}
}
```
......@@ -35,7 +37,7 @@ One of the following three options can be selected:
- **Strict**: Includes Next.js' base ESLint configuration along with a stricter [Core Web Vitals rule-set](/docs/pages/building-your-application/configuring/eslint#core-web-vitals). This is the recommended configuration for developers setting up ESLint for the first time.
```json
```json filename=".eslintrc.json"
{
"extends": "next/core-web-vitals"
}
......@@ -43,7 +45,7 @@ One of the following three options can be selected:
- **Base**: Includes Next.js' base ESLint configuration.
```json
```json filename=".eslintrc.json"
{
"extends": "next"
}
......@@ -110,7 +112,7 @@ If you already have ESLint configured in your application, we recommend extendin
If you're using `eslint-plugin-next` in a project where Next.js isn't installed in your root directory (such as a monorepo), you can tell `eslint-plugin-next` where to find your Next.js application using the `settings` property in your `.eslintrc`:
```json filename=".eslintrc"
```json filename=".eslintrc.json"
{
"extends": "next",
"settings": {
......@@ -153,7 +155,7 @@ next lint --no-cache
If you would like to modify or disable any rules provided by the supported plugins (`react`, `react-hooks`, `next`), you can directly change them using the `rules` property in your `.eslintrc`:
```json filename=".eslintrc"
```json filename=".eslintrc.json"
{
"extends": "next",
"rules": {
......@@ -167,7 +169,7 @@ If you would like to modify or disable any rules provided by the supported plugi
The `next/core-web-vitals` rule set is enabled when `next lint` is run for the first time and the **strict** option is selected.
```json
```json filename=".eslintrc.json"
{
"extends": "next/core-web-vitals"
}
......@@ -193,7 +195,7 @@ yarn add --dev eslint-config-prettier
Then, add `prettier` to your existing ESLint config:
```json
```json filename=".eslintrc.json"
{
"extends": ["next", "prettier"]
}
......@@ -255,7 +257,7 @@ This eliminates the risk of collisions or errors that can occur due to importing
If you already use a separate ESLint configuration and want to include `eslint-config-next`, ensure that it is extended last after other configurations. For example:
```json
```json filename=".eslintrc.json"
{
"extends": ["eslint:recommended", "next"]
}
......
......@@ -32,7 +32,7 @@ The `baseUrl` configuration option allows you to import directly from the root o
An example of this configuration:
```json filename="tsconfig.json / jsconfig.json"
```json filename="tsconfig.json or jsconfig.json"
{
"compilerOptions": {
"baseUrl": "."
......
......@@ -220,7 +220,7 @@ To share a layout around MDX content, you can use the [built-in layouts support]
To add a layout to your MDX page, create a new component and import it into the MDX page. Then you can wrap the MDX page with your layout component:
```jsx filename="pages/index.jsx"
```jsx filename="pages/index.js"
import { MyLayoutComponent } from 'my-components';
import HelloWorld from './hello.mdx';
......@@ -349,7 +349,7 @@ React does not natively understand Markdown. The markdown plaintext needs to fir
`remark` is an ecosystem of tools around markdown. `rehype` is the same, but for HTML. For example, the following code snippet transforms markdown into HTML:
```jsx
```js
import { unified } from 'unified'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
......
......@@ -13,7 +13,7 @@ First, create a [Route Handler](/docs/app/building-your-application/routing/rout
Then, import `draftMode` from `next/headers` and call the `enable()` method.
```tsx filename="app/api/draft/route.ts" switcher
```ts filename="app/api/draft/route.ts" switcher
// route handler enabling draft mode
import { draftMode } from 'next/headers'
......
......@@ -60,7 +60,7 @@ Next.js can be deployed to any hosting provider that supports Node.js. For examp
First, ensure your `package.json` has the `"build"` and `"start"` scripts:
```json
```json filename="package.json"
{
"scripts": {
"dev": "next dev",
......
......@@ -38,13 +38,13 @@ This codemod uninstalls the `@next/font` package and transforms `@next/font` imp
For example:
```jsx
```js
import { Inter } from '@next/font/google'
```
Transforms into:
```jsx
```js
import { Inter } from 'next/font/google'
```
......
......@@ -284,7 +284,7 @@ export default function Page() {
}
```
```js filename="pages/index.js" switcher
```jsx filename="pages/index.js" switcher
import Head from 'next/head'
export default function Page() {
......@@ -453,7 +453,7 @@ export default function ExampleClientComponent() {
}
```
```js filename="app/example-client-component.js" switcher
```jsx filename="app/example-client-component.js" switcher
'use client'
import { useRouter, usePathname, useSearchParams } from 'next/navigation'
......@@ -685,7 +685,7 @@ export default function Index({ projects }) {
In the `app` directory, data fetching with [`fetch()`](/docs/app/api-reference/functions/fetch) will default to `cache: 'force-cache'`, which will cache the request data until manually invalidated. This is similar to `getStaticProps` in the `pages` directory.
```tsx filename="app/page.js"
```jsx filename="app/page.js"
// `app` directory
// This function can be named anything
......@@ -887,7 +887,7 @@ In the `pages` directory, global stylesheets are restricted to only `pages/_app.
If you're using Tailwind CSS, you'll need to add the `app` directory to your `tailwind.config.js` file:
```jsx filename="tailwind.config.js"
```js filename="tailwind.config.js"
module.exports = {
content: [
'./app/**/*.{js,ts,jsx,tsx,mdx}', // <-- Add this line
......
......@@ -17,7 +17,7 @@ export default function Dashboard() {
}
```
```js filename="app/dashboard/page.js" switcher
```jsx filename="app/dashboard/page.js" switcher
import Script from 'next/script'
export default function Dashboard() {
......@@ -220,7 +220,7 @@ export default function Home() {
}
```
```js filename="pages/home.js" switcher
```jsx filename="pages/home.js" switcher
import Script from 'next/script'
export default function Home() {
......
......@@ -146,7 +146,7 @@ export default async function Image() {
}
```
```jsx filename="app/about/opengraph-image.jsx" switcher
```jsx filename="app/about/opengraph-image.js" switcher
import { ImageResponse } from 'next/server'
// Route segment config
......@@ -225,7 +225,7 @@ export default function Image({ params }: { params: { slug: string } }) {
}
```
```jsx filename="app/shop/[slug]/opengraph-image.jsx" switcher
```jsx filename="app/shop/[slug]/opengraph-image.js" switcher
export default function Image({ params }) {
// ...
}
......@@ -262,7 +262,7 @@ export const alt = 'My images alt text'
export default function Image() {}
```
```jsx filename="opengraph-image.jsx / twitter-image.jsx" switcher
```jsx filename="opengraph-image.js / twitter-image.js" switcher
export const alt = 'My images alt text'
export default function Image() {}
......@@ -280,7 +280,7 @@ export const size = { width: 1200, height: 630 }
export default function Image() {}
```
```jsx filename="opengraph-image.jsx / twitter-image.jsx" switcher
```jsx filename="opengraph-image.js / twitter-image.js" switcher
export const size = { width: 1200, height: 630 }
export default function Image() {}
......@@ -299,7 +299,7 @@ export const contentType = 'image/png'
export default function Image() {}
```
```jsx filename="opengraph-image.jsx / twitter-image.jsx" switcher
```jsx filename="opengraph-image.js / twitter-image.js" switcher
export const contentType = 'image/png'
export default function Image() {}
......@@ -326,7 +326,7 @@ export const runtime = 'edge'
export default function Image() {}
```
```jsx filename="app/opengraph-image.jsx" switcher
```jsx filename="app/opengraph-image.js" switcher
export const runtime = 'edge'
export default function Image() {}
......@@ -381,7 +381,7 @@ export default async function Image({ params }: { params: { slug: string } }) {
}
```
```jsx filename="app/posts/[slug]/opengraph-image.jsx" switcher
```jsx filename="app/posts/[slug]/opengraph-image.js" switcher
import { ImageResponse } from 'next/server'
export const runtime = 'edge'
......
......@@ -7,7 +7,7 @@ Add or generate a `sitemap.xml` file that matches the [Sitemaps XML format](http
## Static `sitemap.xml`
```jsx filename="app/sitemap.xml"
```xml filename="app/sitemap.xml"
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://acme.com</loc>
......@@ -70,7 +70,7 @@ export default function sitemap() {
Output:
```jsx filename="acme.com/sitemap.xml"
```xml filename="acme.com/sitemap.xml"
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://acme.com</loc>
......
......@@ -65,7 +65,7 @@ The [dynamic route parameters](/docs/app/building-your-application/routing/dynam
For example:
```tsx filename="app/shop/[tag]/[item]/layout.ts" switcher
```tsx filename="app/shop/[tag]/[item]/layout.tsx" switcher
export default function ShopLayout({
children,
params,
......
......@@ -10,14 +10,14 @@ By default, this file is a [Server Component](/docs/getting-started/react-essent
```tsx filename="app/feed/loading.tsx" switcher
export default function Loading() {
// Or a custom loading skeleton component
return 'Loading...'
return <p>'Loading...'</p>
}
```
```js filename="app/feed/loading.js" switcher
```jsx filename="app/feed/loading.js" switcher
export default function Loading() {
// Or a custom loading skeleton component
return 'Loading...'
return <p>'Loading...'</p>
}
```
......
......@@ -422,31 +422,31 @@ URL composition favors developer intent over default directory traversal semanti
For example, given the following `metadataBase`:
```tsx filename="app/api/layout.tsx" switcher
```tsx filename="app/layout.tsx" switcher
import { Metadata } from 'next'
export const metadata: Metadata = {
metadataBase: new URL('https://acme.com/api'),
metadataBase: new URL('https://acme.com'),
}
```
```jsx filename="app/api/layout.js" switcher
```jsx filename="app/layout.js" switcher
export const metadata = {
metadataBase: new URL('https://acme.com/api'),
metadataBase: new URL('https://acme.com'),
}
```
Any `metadata` fields that inherit the above `metadataBase` and set their own value will be resolved as follows:
| `metadata` field | Resolved URL |
| ------------------------------------ | ------------------------------------ |
| `/` | `https://acme.com/api` |
| `./` | `https://acme.com/api` |
| `payments` | `https://acme.com/api/payments` |
| `/payments` | `https://acme.com/api/payments` |
| `./payments` | `https://acme.com/api/payments` |
| `../payments` | `https://acme.com/payments` |
| `https://beta.acme.com/api/payments` | `https://beta.acme.com/api/payments` |
| `metadata` field | Resolved URL |
| -------------------------------- | -------------------------------- |
| `/` | `https://acme.com` |
| `./` | `https://acme.com` |
| `payments` | `https://acme.com/payments` |
| `/payments` | `https://acme.com/payments` |
| `./payments` | `https://acme.com/payments` |
| `../payments` | `https://acme.com/payments` |
| `https://beta.acme.com/payments` | `https://beta.acme.com/payments` |
### `openGraph`
......
......@@ -5,7 +5,7 @@ description: API Reference for the revalidatePath function.
`revalidatePath` allows you to revalidate data associated with a specific path. This is useful for scenarios where you want to update your cached data without waiting for a revalidation period to expire.
```tsx filename="app/api/revalidate/route.ts" switcher
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
......@@ -16,7 +16,7 @@ export async function GET(request: NextRequest) {
}
```
```jsx filename="app/api/revalidate/route.js" switcher
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
......@@ -49,7 +49,7 @@ revalidatePath(path: string): void;
### Node.js Runtime
```tsx filename="app/api/revalidate/route.ts" switcher
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
......@@ -60,7 +60,7 @@ export async function GET(request: NextRequest) {
}
```
```jsx filename="app/api/revalidate/route.js" switcher
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
......@@ -73,7 +73,7 @@ export async function GET(request) {
### Edge Runtime
```tsx filename="app/api/revalidate/route.ts" switcher
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
......@@ -86,7 +86,7 @@ export async function GET(request: NextRequest) {
}
```
```jsx filename="app/api/revalidate/route.js" switcher
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidatePath } from 'next/cache'
......
......@@ -5,7 +5,7 @@ description: API Reference for the revalidateTag function.
`revalidateTag` allows you to revalidate data associated with a specific cache tag. This is useful for scenarios where you want to update your cached data without waiting for a revalidation period to expire.
```tsx filename="app/api/revalidate/route.ts" switcher
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
......@@ -16,7 +16,7 @@ export async function GET(request: NextRequest) {
}
```
```jsx filename="app/api/revalidate/route.js" switcher
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
......@@ -53,7 +53,7 @@ fetch(url, { next: { tags: [...] } });
### Node.js Runtime
```tsx filename="app/api/revalidate/route.ts" switcher
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
......@@ -64,7 +64,7 @@ export async function GET(request: NextRequest) {
}
```
```jsx filename="app/api/revalidate/route.js" switcher
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
......@@ -77,7 +77,7 @@ export async function GET(request) {
### Edge Runtime
```tsx filename="app/api/revalidate/route.ts" switcher
```ts filename="app/api/revalidate/route.ts" switcher
import { NextRequest, NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
......@@ -90,7 +90,7 @@ export async function GET(request: NextRequest) {
}
```
```jsx filename="app/api/revalidate/route.js" switcher
```js filename="app/api/revalidate/route.js" switcher
import { NextResponse } from 'next/server'
import { revalidateTag } from 'next/cache'
......
......@@ -12,7 +12,7 @@ import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <>Current pathname: {pathname}</>
return <p>Current pathname: {pathname}</p>
}
```
......@@ -23,7 +23,7 @@ import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <>Current pathname: {pathname}</>
return <p>Current pathname: {pathname}</p>
}
```
......
......@@ -7,7 +7,7 @@ The `useReportWebVitals` hook allows you to report [Core Web Vitals](https://web
<PagesOnly>
```tsx filename="pages/_app.js"
```jsx filename="pages/_app.js"
import { useReportWebVitals } from 'next/web-vitals'
function MyApp({ Component, pageProps }) {
......@@ -23,7 +23,7 @@ function MyApp({ Component, pageProps }) {
<AppOnly>
```tsx filename="app/_components/web-vitals.js"
```jsx filename="app/_components/web-vitals.js"
'use client'
import { useReportWebVitals } from 'next/web-vitals'
......@@ -35,7 +35,7 @@ export function WebVitals() {
}
```
```tsx filename="app/layout.js"
```jsx filename="app/layout.js"
import { WebVitals } from './_components/web-vitals'
export default function Layout({ children }) {
......@@ -82,7 +82,7 @@ You can handle all the results of these metrics using the `name` property.
<PagesOnly>
```tsx filename="pages/_app.js"
```jsx filename="pages/_app.js"
import { useReportWebVitals } from 'next/web-vitals'
function MyApp({ Component, pageProps }) {
......
......@@ -23,7 +23,7 @@ export default function SearchBar() {
}
```
```js filename="app/dashboard/search-bar.js" switcher
```jsx filename="app/dashboard/search-bar.js" switcher
'use client'
import { useSearchParams } from 'next/navigation'
......@@ -101,7 +101,7 @@ export default function SearchBar() {
}
```
```js filename="app/dashboard/search-bar.js" switcher
```jsx filename="app/dashboard/search-bar.js" switcher
'use client'
import { useSearchParams } from 'next/navigation'
......@@ -144,7 +144,7 @@ export default function Page() {
}
```
```js filename="app/dashboard/page.js" switcher
```jsx filename="app/dashboard/page.js" switcher
import { Suspense } from 'react'
import SearchBar from './search-bar'
......@@ -196,7 +196,7 @@ export default function SearchBar() {
}
```
```js filename="app/dashboard/search-bar.js" switcher
```jsx filename="app/dashboard/search-bar.js" switcher
'use client'
import { useSearchParams } from 'next/navigation'
......@@ -231,7 +231,7 @@ export default function Page() {
}
```
```js filename="app/dashboard/page.js" switcher
```jsx filename="app/dashboard/page.js" switcher
import SearchBar from './search-bar'
export const dynamic = 'force-dynamic'
......
......@@ -15,7 +15,7 @@ import { useSelectedLayoutSegment } from 'next/navigation'
export default function ExampleClientComponent() {
const segment = useSelectedLayoutSegment()
return <>Active segment: {segment}</>
return <p>Active segment: {segment}</p>
}
```
......@@ -27,7 +27,7 @@ import { useSelectedLayoutSegment } from 'next/navigation'
export default function ExampleClientComponent() {
const segment = useSelectedLayoutSegment()
return <>Active segment: {segment}</>
return <p>Active segment: {segment}</p>
}
```
......@@ -145,7 +145,7 @@ export default async function Layout({
}
```
```js filename="app/blog/layout.js" switcher
```jsx filename="app/blog/layout.js" switcher
// Import the Client Component into a parent Layout (Server Component)
import { BlogNavLink } from './blog-nav-link'
import getFeaturedPosts from './get-featured-posts'
......
......@@ -395,7 +395,7 @@ If you need to revalidate the cache of a page that has been [statically generate
This header controls DNS prefetching, allowing browsers to proactively perform domain name resolution on external links, images, CSS, JavaScript, and more. This prefetching is performed in the background, so the [DNS](https://developer.mozilla.org/en-US/docs/Glossary/DNS) is more likely to be resolved by the time the referenced items are needed. This reduces latency when the user clicks a link.
```jsx
```js
{
key: 'X-DNS-Prefetch-Control',
value: 'on'
......@@ -408,7 +408,7 @@ This header informs browsers it should only be accessed using HTTPS, instead of
If you're deploying to [Vercel](https://vercel.com/docs/concepts/edge-network/headers#strict-transport-security?utm_source=next-site&utm_medium=docs&utm_campaign=next-website), this header is not necessary as it's automatically added to all deployments unless you declare [`headers`](/docs/pages/api-reference/next-config-js/headers) in your `next.config.js`.
```jsx
```js
{
key: 'Strict-Transport-Security',
value: 'max-age=63072000; includeSubDomains; preload'
......@@ -419,7 +419,7 @@ If you're deploying to [Vercel](https://vercel.com/docs/concepts/edge-network/he
This header stops pages from loading when they detect reflected cross-site scripting (XSS) attacks. Although this protection is not necessary when sites implement a strong [`Content-Security-Policy`](#content-security-policy) disabling the use of inline JavaScript (`'unsafe-inline'`), it can still provide protection for older web browsers that don't support CSP.
```jsx
```js
{
key: 'X-XSS-Protection',
value: '1; mode=block'
......@@ -430,7 +430,7 @@ This header stops pages from loading when they detect reflected cross-site scrip
This header indicates whether the site should be allowed to be displayed within an `iframe`. This can prevent against clickjacking attacks. This header has been superseded by CSP's `frame-ancestors` option, which has better support in modern browsers.
```jsx
```js
{
key: 'X-Frame-Options',
value: 'SAMEORIGIN'
......@@ -441,7 +441,7 @@ This header indicates whether the site should be allowed to be displayed within
This header allows you to control which features and APIs can be used in the browser. It was previously named `Feature-Policy`. You can view the full list of permission options [here](https://github.com/w3c/webappsec-permissions-policy/blob/main/features.md).
```jsx
```js
{
key: 'Permissions-Policy',
value: 'camera=(), microphone=(), geolocation=(), browsing-topics=()'
......@@ -452,7 +452,7 @@ This header allows you to control which features and APIs can be used in the bro
This header prevents the browser from attempting to guess the type of content if the `Content-Type` header is not explicitly set. This can prevent XSS exploits for websites that allow users to upload and share files. For example, a user trying to download an image, but having it treated as a different `Content-Type` like an executable, which could be malicious. This header also applies to downloading browser extensions. The only valid value for this header is `nosniff`.
```jsx
```js
{
key: 'X-Content-Type-Options',
value: 'nosniff'
......@@ -463,7 +463,7 @@ This header prevents the browser from attempting to guess the type of content if
This header controls how much information the browser includes when navigating from the current website (origin) to another. You can read about the different options [here](https://scotthelme.co.uk/a-new-security-header-referrer-policy/).
```jsx
```js
{
key: 'Referrer-Policy',
value: 'origin-when-cross-origin'
......@@ -478,7 +478,7 @@ You can read about the many different CSP options [here](https://developer.mozil
You can add Content Security Policy directives using a template string.
```jsx
```js
// Before defining your Security Headers
// add Content Security Policy directives using a template string.
......
......@@ -195,7 +195,7 @@ componentDidUpdate(prevProps) {
Shallow routing **only** works for URL changes in the current page. For example, let's assume we have another page called `pages/about.js`, and you run this:
```jsx
```js
router.push('/?counter=10', '/about?counter=10', { shallow: true })
```
......
......@@ -299,7 +299,7 @@ Next.js doesn't know about variants of a page so it's up to you to add the `href
For pages using `getStaticProps` with [Dynamic Routes](/docs/pages/building-your-application/routing/dynamic-routes), all locale variants of the page desired to be prerendered need to be returned from [`getStaticPaths`](/docs/pages/building-your-application/data-fetching/get-static-paths). Along with the `params` object returned for `paths`, you can also return a `locale` field specifying which locale you want to render. For example:
```js filename="pages/blog/[slug].js"
```jsx filename="pages/blog/[slug].js"
export const getStaticPaths = ({ locales }) => {
return {
paths: [
......
......@@ -102,7 +102,7 @@ https://<your-site.com>/api/revalidate?secret=<token>
Next, add the secret as an [Environment Variable](/docs/pages/building-your-application/configuring/environment-variables) to your application. Finally, create the revalidation API Route:
```jsx filename="pages/api/revalidate.js"
```js filename="pages/api/revalidate.js"
export default async function handler(req, res) {
// Check for secret to confirm this is a valid request
if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
......
......@@ -28,7 +28,7 @@ export default function Page({
}
```
```jsx filename="pages/index.jsx" switcher
```jsx filename="pages/index.js" switcher
export const getStaticProps = async () => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
......@@ -100,7 +100,7 @@ export async function getStaticProps() {
}
```
```js filename="pages/blog.js" switcher
```jsx filename="pages/blog.js" switcher
// posts will be populated at build time by getStaticProps()
export default function Blog({ posts }) {
return (
......@@ -141,7 +141,7 @@ This means that instead of fetching an **API route** from `getStaticProps` (that
Take the following example. An API route is used to fetch some data from a CMS. That API route is then called directly from `getStaticProps`. This produces an additional call, reducing performance. Instead, the logic for fetching the data from the CMS can be shared by using a `lib/` directory. Then it can be shared with `getStaticProps`.
```jsx filename="lib/load-posts.js"
```js filename="lib/load-posts.js"
// The following function is shared
// with getStaticProps and API routes
// from a `lib/` directory
......@@ -152,7 +152,9 @@ export async function loadPosts() {
return data
}
```
```jsx filename="pages/blog.js"
// pages/blog.js
import { loadPosts } from '../lib/load-posts'
......
......@@ -47,7 +47,7 @@ export default function Page({
}
```
```jsx filename="pages/repo/[name].jsx" switcher
```jsx filename="pages/repo/[name].js" switcher
export const getStaticPaths = async () => {
return {
paths: [
......
......@@ -28,7 +28,7 @@ export default function Page({
}
```
```jsx filename="pages/index.jsx" switcher
```jsx filename="pages/index.js" switcher
export const getServerSideProps = async () => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
......@@ -77,7 +77,7 @@ Take the following example. An API route is used to fetch some data from a CMS.
You can explicitly set the runtime on a per-page basis by modifying the `config`, for example:
```js filename="pages/index.tsx"
```jsx filename="pages/index.js"
export const config = {
runtime: 'nodejs', // or "edge"
}
......
......@@ -116,7 +116,7 @@ https://<your-site.com>/api/revalidate?secret=<token>
Next, add the secret as an [Environment Variable](/docs/pages/building-your-application/configuring/environment-variables) to your application. Finally, create the revalidation API Route:
```jsx filename="pages/api/revalidate.js"
```js filename="pages/api/revalidate.js"
export default async function handler(req, res) {
// Check for secret to confirm this is a valid request
if (req.query.secret !== process.env.MY_SECRET_TOKEN) {
......
......@@ -39,12 +39,14 @@ npm install --save-dev cypress
Add Cypress to the `package.json` scripts field:
```json
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"cypress": "cypress open",
```json filename="package.json"
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"cypress": "cypress open"
}
}
```
......@@ -90,7 +92,7 @@ export default function About() {
Add a test to check your navigation is working correctly:
```jsx filename="cypress/e2e/app.cy.js"
```js filename="cypress/e2e/app.cy.js"
describe('Navigation', () => {
it('should navigate to the about page', () => {
// Start from the index page
......@@ -155,13 +157,14 @@ Run `npm run cypress -- --component` to start Cypress and execute your component
You will have noticed that running Cypress so far has opened an interactive browser which is not ideal for CI environments. You can also run Cypress headlessly using the `cypress run` command:
```json filename="package.json"
"scripts": {
//...
"e2e": "start-server-and-test dev http://localhost:3000 \"cypress open --e2e\"",
"e2e:headless": "start-server-and-test dev http://localhost:3000 \"cypress run --e2e\"",
"component": "cypress open --component",
"component:headless": "cypress run --component"
{
"scripts": {
//...
"e2e": "start-server-and-test dev http://localhost:3000 \"cypress open --e2e\"",
"e2e:headless": "start-server-and-test dev http://localhost:3000 \"cypress run --e2e\"",
"component": "cypress open --component",
"component:headless": "cypress run --component"
}
}
```
......@@ -195,12 +198,14 @@ npm install --save-dev @playwright/test
Add Playwright to the `package.json` scripts field:
```json
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test:e2e": "playwright test",
```json filename="package.json"
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test:e2e": "playwright test"
}
}
```
......@@ -312,7 +317,7 @@ npm install --save-dev jest jest-environment-jsdom @testing-library/react @testi
Create a `jest.config.mjs` file in your project's root directory and add the following:
```jsx filename="jest.config.mjs"
```js filename="jest.config.mjs"
import nextJest from 'next/jest.js'
const createJestConfig = nextJest({
......@@ -350,7 +355,7 @@ If you opt out of the [Rust Compiler](/docs/architecture/nextjs-compiler), you w
Here are the recommended options to configure Jest for Next.js:
```jsx filename="jest.config.js"
```js filename="jest.config.js"
module.exports = {
collectCoverage: true,
// on node 14.x coverage provider v8 offers good speed and more or less good report
......@@ -426,7 +431,7 @@ setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
Then, inside `jest.setup.js`, add the following import:
```jsx filename="jest.setup.js"
```js filename="jest.setup.js"
import '@testing-library/jest-dom/extend-expect'
```
......@@ -436,7 +441,7 @@ If you need to add more setup options before each test, it's common to add them
If your project is using [Module Path Aliases](/docs/pages/building-your-application/configuring/absolute-imports-and-module-aliases), you will need to configure Jest to resolve the imports by matching the paths option in the `jsconfig.json` file with the `moduleNameMapper` option in the `jest.config.js` file. For example:
```json filename="tsconfig.json" or jsconfig.json
```json filename="tsconfig.json or jsconfig.json"
{
"compilerOptions": {
"baseUrl": ".",
......@@ -447,7 +452,7 @@ If your project is using [Module Path Aliases](/docs/pages/building-your-applica
}
```
```jsx filename="jest.config.js"
```js filename="jest.config.js"
moduleNameMapper: {
'^@/components/(.*)$': '<rootDir>/components/$1',
}
......@@ -459,12 +464,14 @@ moduleNameMapper: {
Add the Jest executable in watch mode to the `package.json` scripts:
```jsx
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest --watch"
```json filename="package.json"
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest --watch"
}
}
```
......@@ -476,7 +483,7 @@ Your project is now ready to run tests. Follow Jest's convention by adding tests
For example, we can add a test to check if the `<Home />` component successfully renders a heading:
```jsx filename="__tests__/index.test.jsx"
```jsx filename="__tests__/index.test.js"
import { render, screen } from '@testing-library/react'
import Home from '../pages/index'
import '@testing-library/jest-dom'
......
......@@ -97,7 +97,7 @@ Pages are also validated during [Static HTML export](/docs/pages/building-your-a
You can set up custom AMP validator in `next.config.js` as shown below:
```jsx
```js
module.exports = {
amp: {
validator: './custom_validator.js',
......@@ -109,7 +109,7 @@ module.exports = {
To turn off AMP validation add the following code to `next.config.js`
```jsx
```js
experimental: {
amp: {
skipValidation: true
......
......@@ -42,7 +42,7 @@ See ["Customizing Plugins"](#customizing-plugins) below for more information.
<details>
<summary>Click to view the configuration to enable CSS Grid Layout</summary>
```json
```json filename="postcss.config.json"
{
"plugins": [
"postcss-flexbugs-fixes",
......@@ -74,7 +74,7 @@ Next.js allows you to configure the target browsers (for [Autoprefixer](https://
To customize browserslist, create a `browserslist` key in your `package.json` like so:
```json
```json filename="package.json"
{
"browserslist": [">0.3%", "not dead", "not op_mini all"]
}
......
......@@ -68,11 +68,13 @@ app.prepare().then(() => {
To run the custom server you'll need to update the `scripts` in `package.json` like so:
```json
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
```json filename="package.json"
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
```
......
......@@ -11,7 +11,7 @@ Any debugger that can attach to Node.js can also be used to debug a Next.js appl
Create a file named `.vscode/launch.json` at the root of your project with the following content:
```json
```json filename="launch.json"
{
"version": "0.2.0",
"configurations": [
......@@ -68,8 +68,12 @@ NODE_OPTIONS='--inspect' next dev
If you're using `npm run dev` or `yarn dev` then you should update the `dev` script on your `package.json`:
```json
"dev": "NODE_OPTIONS='--inspect' next dev"
```json filename="package.json"
{
"scripts": {
"dev": "NODE_OPTIONS='--inspect' next dev"
}
}
```
Launching the Next.js dev server with the `--inspect` flag will look something like this:
......@@ -90,8 +94,12 @@ Debugging server-side code here works much like debugging client-side code with
Windows users may run into an issue when using `NODE_OPTIONS='--inspect'` as that syntax is not supported on Windows platforms. To get around this, install the [`cross-env`](https://www.npmjs.com/package/cross-env) package as a development dependency (`-D` with `npm` and `yarn`) and replace the `dev` script with the following.
```json
"dev": "cross-env NODE_OPTIONS='--inspect' next dev",
```json filename="package.json"
{
"scripts": {
"dev": "cross-env NODE_OPTIONS='--inspect' next dev"
}
}
```
`cross-env` will set the `NODE_OPTIONS` environment variable regardless of which platform you are on (including Mac, Linux, and Windows) and allow you to debug consistently across devices and operating systems.
......
......@@ -21,7 +21,7 @@ export default function Page({ stars }: { stars: number }) {
}
```
```jsx filename="pages/index.jsx" switcher
```jsx filename="pages/index.js" switcher
Page.getInitialProps = async (ctx) => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const json = await res.json()
......
......@@ -28,7 +28,7 @@ export default function Page({
}
```
```jsx filename="pages/index.jsx" switcher
```jsx filename="pages/index.js" switcher
export const getServerSideProps = async () => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
......
......@@ -45,7 +45,7 @@ export default function Page({
}
```
```jsx filename="pages/repo/[name].jsx" switcher
```jsx filename="pages/repo/[name].js" switcher
export const getStaticPaths = async () => {
return {
paths: [
......
......@@ -28,7 +28,7 @@ export default function Page({
}
```
```jsx filename="pages/index.jsx" switcher
```jsx filename="pages/index.js" switcher
export const getStaticProps = async () => {
const res = await fetch('https://api.github.com/repos/vercel/next.js')
const repo = await res.json()
......
......@@ -16,7 +16,7 @@ description: Enable AMP in a page, and control the way Next.js adds AMP to the p
To enable AMP, add the following config to your page:
```jsx
```jsx filename="pages/index.js"
export const config = { amp: true }
```
......@@ -31,7 +31,7 @@ To learn more about the `amp` config, read the sections below.
Take a look at the following example:
```jsx
```jsx filename="pages/about.js"
export const config = { amp: true }
function About(props) {
......@@ -51,7 +51,7 @@ The page above is an AMP-only page, which means:
Take a look at the following example:
```jsx
```jsx filename="pages/about.js"
import { useAmp } from 'next/amp'
export const config = { amp: 'hybrid' }
......
......@@ -65,7 +65,7 @@ The following methods are included inside `router`:
Handles client-side transitions, this method is useful for cases where [`next/link`](/docs/pages/api-reference/components/link) is not enough.
```jsx
```js
router.push(url, as, options)
```
......@@ -209,7 +209,7 @@ export default function ReadMore({ post }) {
Similar to the `replace` prop in [`next/link`](/docs/pages/api-reference/components/link), `router.replace` will prevent adding a new URL entry into the `history` stack.
```jsx
```js
router.replace(url, as, options)
```
......@@ -237,7 +237,7 @@ Prefetch pages for faster client-side transitions. This method is only useful fo
> This is a production only feature. Next.js doesn't prefetch pages in development.
```jsx
```js
router.prefetch(url, as, options)
```
......@@ -287,7 +287,7 @@ export default function Login() {
In some cases (for example, if using a [Custom Server](/docs/pages/building-your-application/configuring/custom-server)), you may wish to listen to [popstate](https://developer.mozilla.org/en-US/docs/Web/Events/popstate) and do something before the router acts on it.
```jsx
```js
router.beforePopState(cb)
```
......
......@@ -15,7 +15,7 @@ Next.js supports **modern browsers** with zero configuration.
If you would like to target specific browsers or features, Next.js supports [Browserslist](https://browsersl.ist) configuration in your `package.json` file. Next.js uses the following Browserslist configuration by default:
```json
```json filename="package.json"
{
"browserslist": [
"chrome 64",
......
......@@ -39,9 +39,11 @@ Open the command pallete (`⌘ + ⇧ + P` on Mac or `Ctrl + Shift + P` on Window
Then, add the following line to your `settings.json` file:
```json filename="settings.json"
"files.associations": {
{
"files.associations": {
"*.mdx": "markdown"
}
}
```
Next, open the command palette again, and search for `Markdown: Preview File` or `Markdown: Open Preview to the Side`. This will open a preview window where you can see your formatted changes.
......@@ -216,6 +218,15 @@ npx create-next-app
Most examples in the docs are written in `tsx` and `jsx`, and a few in `bash`. However, you can use any supported language, here's the [full list](https://github.com/shikijs/shiki/blob/main/docs/languages.md#all-languages).
When writing JavaScript code blocks, we use the following language and extension combinations.
| | Language | Extension |
| ------------------------------ | -------- | --------- |
| JavaScript files with JSX code | ```jsx | .js |
| JavaScript files without JSX | ```js | .js |
| TypeScript files with JSX | ```tsx | .tsx |
| TypeScript files without JSX | ```ts | .ts |
### TS and JS Switcher
Add a language switcher to toggle between TypeScript and JavaScript. Code blocks should be TypeScript first with a JavaScript version to accommodate users.
......@@ -227,7 +238,7 @@ Currently, we write TS and JS examples one after the other, and link them with `
```
```jsx filename="app/page.jsx" switcher
```jsx filename="app/page.js" switcher
```
````
......
......@@ -42,6 +42,7 @@ export default class Page extends React.Component {
```jsx
'use client'
export default class Page extends React.Component {
render() {
return <p>Hello world</p>
......
......@@ -11,12 +11,12 @@ Remove any conflicting paths shown in the error message and only return them fro
Example conflicting paths:
```jsx
// pages/hello/world.js
// pages/hello/world.jsx
export default function Hello() {
return 'hello world!'
}
// pages/[...catchAll].js
// pages/[...catchAll].jsx
export const getStaticProps = () => ({ props: {} })
export const getStaticPaths = () => ({
......@@ -36,7 +36,7 @@ export default function CatchAll() {
Example conflicting paths:
```jsx
// pages/blog/[slug].js
// pages/blog/[slug].jsx
export const getStaticPaths = () => ({
paths: ['/blog/conflicting', '/blog/another'],
fallback: false,
......@@ -46,7 +46,7 @@ export default function Blog() {
return 'Blog!'
}
// pages/[...catchAll].js
// pages/[...catchAll].jsx
export const getStaticProps = () => ({ props: {} })
export const getStaticPaths = () => ({
......
......@@ -16,8 +16,8 @@ Or, [update your component to use local CSS (Component-Level CSS) via CSS Module
Consider the stylesheet named [`styles.css`](https://nextjs.org/docs/basic-features/built-in-css-support#adding-a-global-stylesheet)
```jsx
//styles.css
```css
/* styles.css */
body {
font-family: 'SF Pro Text', 'SF Pro Icons', 'Helvetica Neue', 'Helvetica',
'Arial', sans-serif;
......
......@@ -40,7 +40,7 @@ export default MyDocument
Or as a function component:
```js
```jsx
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document'
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment