Skip to content

Commit

Permalink
Add edge-functions/modify-request-header example (#429)
Browse files Browse the repository at this point in the history
Co-authored-by: Luis Alvarez D. <luis@vercel.com>
  • Loading branch information
nuta and lfades committed Nov 21, 2022
1 parent 385a2e9 commit f886bb6
Show file tree
Hide file tree
Showing 15 changed files with 327 additions and 5 deletions.
6 changes: 3 additions & 3 deletions edge-functions/add-header/README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
name: Adding Headers in Edge Functions
name: Adding Response Headers in Edge Functions
slug: edge-functions-add-header
description: Learn to add headers at the edge.
description: Learn to add response headers at the edge.
framework: Next.js
useCase:
- Edge Functions
Expand All @@ -13,7 +13,7 @@ demoUrl: https://edge-functions-add-header.vercel.app

# Add Header Example

Below is the code from [middleware.ts](middleware.ts) showing how to add headers at the edge:
Below is the code from [middleware.ts](middleware.ts) showing how to add response headers at the edge:

```ts
import { NextResponse } from 'next/server'
Expand Down
4 changes: 2 additions & 2 deletions edge-functions/add-header/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ function App({ Component, pageProps }: AppProps) {

return (
<Layout
title="Adding headers at the edge"
title="Adding response headers at the edge"
path="edge-functions/add-header"
description="How to add headers to an incoming request"
description="How to add response headers in a middleware"
>
<Component {...pageProps} />
</Layout>
Expand Down
4 changes: 4 additions & 0 deletions edge-functions/modify-request-header/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"root": true,
"extends": "next/core-web-vitals"
}
34 changes: 34 additions & 0 deletions edge-functions/modify-request-header/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# Dependencies
/node_modules
/.pnp
.pnp.js

# Testing
/coverage

# Next.js
/.next/
/out/

# Production
/build

# Misc
.DS_Store
*.pem

# Debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Local ENV files
.env.local
.env.development.local
.env.test.local
.env.production.local

# Vercel
.vercel
2 changes: 2 additions & 0 deletions edge-functions/modify-request-header/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Enabled to avoid deps failing to use next@canary
legacy-peer-deps=true
85 changes: 85 additions & 0 deletions edge-functions/modify-request-header/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
---
name: Modifying Request Headers in Middleware
slug: edge-functions-modify-request-header
description: Learn to add/update/delete request headers in a middleware.
framework: Next.js
useCase:
- Edge Functions
- Documentation
css: Tailwind
deployUrl: https://vercel.com/new/clone?repository-url=https://github.com/vercel/examples/tree/main/edge-functions/modify-request-header&project-name=modify-request-header&repository-name=modify-request-header
demoUrl: https://edge-middleware-modify-request-header.vercel.app
relatedTemplates:
- edge-functions-add-header
---

# Add Header Example

Below is the code from [middleware.ts](middleware.ts) showing how to add/update/delete headers in a middleware (available since Next.js v13.0.0):

```ts
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
// Clone the request headers
// You can modify them with headers API: https://developer.mozilla.org/en-US/docs/Web/API/Headers
const requestHeaders = new Headers(request.headers)

// Add new request headers
requestHeaders.set('x-hello-from-middleware1', 'hello')
requestHeaders.set('x-hello-from-middleware2', 'world!')

// Update an existing request header
requestHeaders.set('user-agent', 'New User Agent overriden by middleware!')

// Delete an existing request header
requestHeaders.delete('x-from-client')

// You can also set request headers in NextResponse.rewrite
return NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
})
}
```

## Demo

https://edge-functions-modify-request-header.vercel.app

## How to Use

You can choose from one of the following two methods to use this repository:

### One-Click Deploy

Deploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=vercel-examples):

[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/clone?repository-url=https://github.com/vercel/examples/tree/main/edge-functions/modify-request-header&project-name=modify-request-header&repository-name=modify-request-header)

### Clone and Deploy

Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:

```bash
npx create-next-app --example https://github.com/vercel/examples/tree/main/edge-functions/modify-request-header modify-request-header
# or
yarn create next-app --example https://github.com/vercel/examples/tree/main/edge-functions/modify-request-header modify-request-header
```

Next, run Next.js in development mode:

```bash
npm install
npm run dev

# or

yarn
yarn dev
```

Deploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=edge-middleware-eap) ([Documentation](https://nextjs.org/docs/deployment)).
26 changes: 26 additions & 0 deletions edge-functions/modify-request-header/middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'

export function middleware(request: NextRequest) {
// Clone the request headers
// You can modify them with headers API: https://developer.mozilla.org/en-US/docs/Web/API/Headers
const requestHeaders = new Headers(request.headers)

// Add new request headers
requestHeaders.set('x-hello-from-middleware1', 'hello')
requestHeaders.set('x-hello-from-middleware2', 'world!')

// Update an existing request header
requestHeaders.set('user-agent', 'New User Agent overriden by middleware!')

// Delete an existing request header
requestHeaders.delete('x-from-client')

// You can also set request headers in NextResponse.rewrite
return NextResponse.next({
request: {
// New request headers
headers: requestHeaders,
},
})
}
5 changes: 5 additions & 0 deletions edge-functions/modify-request-header/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
26 changes: 26 additions & 0 deletions edge-functions/modify-request-header/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"repository": "https://github.com/vercel/examples.git",
"license": "MIT",
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@vercel/examples-ui": "^1.0.2",
"next": "canary",
"react": "latest",
"react-dom": "latest"
},
"devDependencies": {
"@types/node": "^17.0.14",
"@types/react": "latest",
"autoprefixer": "^10.4.2",
"eslint": "^8.9.0",
"eslint-config-next": "canary",
"postcss": "^8.4.6",
"tailwindcss": "^3.0.18",
"typescript": "^4.5.5"
}
}
22 changes: 22 additions & 0 deletions edge-functions/modify-request-header/pages/_app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import type { AppProps } from 'next/app'
import type { LayoutProps } from '@vercel/examples-ui/layout'

import { getLayout } from '@vercel/examples-ui'

import '@vercel/examples-ui/globals.css'

function App({ Component, pageProps }: AppProps) {
const Layout = getLayout<LayoutProps>(Component)

return (
<Layout
title="Adding request headers in middleware"
path="edge-functions/modify-request-header"
description="How to modify request headers in a middleware"
>
<Component {...pageProps} />
</Layout>
)
}

export default App
82 changes: 82 additions & 0 deletions edge-functions/modify-request-header/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import type { FC, ReactNode } from 'react'

import { Code, Layout, Link, Page, Snippet, Text } from '@vercel/examples-ui'

const Console: FC<{ children: ReactNode }> = ({ children }) => {
return (
<pre className="bg-black text-white font-mono text-left py-2 px-4 rounded-lg text-sm leading-6">
{children}
</pre>
)
}

export function getServerSideProps(ctx: any) {
return {
props: {
requestHeaders: ctx.req.headers,
},
}
}

function IndexPage({ requestHeaders }: any) {
return (
<Page>
<section className="flex flex-col gap-6">
<Text variant="h1">Modyfing request headers in middleware</Text>
<Text>
In some cases we might want to add, modify, or delete request headers
from clients to change behavior or pass data to API Routes or{' '}
<Code>getServerSideProps</Code>. To modify to the request headers
specify the new headers (see{' '}
<Link href="https://developer.mozilla.org/en-US/docs/Web/API/Headers">
Headers API
</Link>
) in <Code>request.headers</Code> parameter of{' '}
<Code>NextResponse.next()</Code> or{' '}
<Code>NextResponse.rewrite()</Code>.
</Text>
<Text>Only available since Next.js v13.0.0.</Text>
<Snippet>
{`// You can use headers API:
// https://developer.mozilla.org/en-US/docs/Web/API/Headers
const requestHeaders = new Headers(request.headers)
requestHeaders.set('x-hello-from-middleware1', 'hello')
requestHeaders.set('x-hello-from-middleware2', 'world!')
requestHeaders.set('user-agent', 'New User Agent overriden by middleware!')
const response = NextResponse.next({
request: {
headers: requestHeaders,
},
})
`}
</Snippet>
</section>

<hr className="border-t border-accents-2 my-6" />
<section className="flex flex-col items-center gap-3">
<Text>
Request Headers in <Code>getServerSideProps</Code>:
</Text>
<Console>
<p>
<strong>{'x-hello-from-middleware1: '}</strong>
{requestHeaders['x-hello-from-middleware1']}
</p>
<p>
<strong>{'x-hello-from-middleware2: '}</strong>
{requestHeaders['x-hello-from-middleware2']}
</p>
<p>
<strong>{'user-agent: '}</strong>
{requestHeaders['user-agent']}
</p>
</Console>
</section>
</Page>
)
}

IndexPage.Layout = Layout

export default IndexPage
8 changes: 8 additions & 0 deletions edge-functions/modify-request-header/postcss.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// If you want to use other PostCSS plugins, see the following:
// https://tailwindcss.com/docs/using-with-preprocessors
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
Binary file not shown.
8 changes: 8 additions & 0 deletions edge-functions/modify-request-header/tailwind.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
presets: [require('@vercel/examples-ui/tailwind')],
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
'./node_modules/@vercel/examples-ui/**/*.js',
],
}
20 changes: 20 additions & 0 deletions edge-functions/modify-request-header/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"incremental": true,
"jsx": "preserve"
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"]
}

2 comments on commit f886bb6

@vercel
Copy link

@vercel vercel bot commented on f886bb6 Nov 21, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

edge-functions-add-header – ./edge-functions/add-header

edge-functions-add-header-git-main.vercel.sh
edge-functions-add-header.vercel.app
edge-functions-add-header.vercel.sh

@vercel
Copy link

@vercel vercel bot commented on f886bb6 Nov 21, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

solutions-monorepo – ./solutions/monorepo/apps/app

solutions-monorepo.vercel.app
solutions-monorepo.vercel.sh
solutions-monorepo-git-main.vercel.sh

Please sign in to comment.