Unverified Commit 0b94b863 authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Merge branch 'canary' into wbinnssmith/unify-node-runtime

parents efb93662 99bfe967
# PR Auto-Labeler
Applies labels to a pull request based on its changed files and author.
## Usage
Reference this action from its canonical location on the `canary` branch so
that all release branches share one source of truth for labeling rules:
```yaml
jobs:
label:
runs-on: ubuntu-latest
permissions:
pull-requests: write
steps:
- uses: vercel/next.js/.github/actions/pr-auto-label@canary
```
No checkout is required — GitHub Actions fetches the action bundle
(`dist/index.js`, pinned to the ref after `@`) from this repo directly.
Referencing `@canary` means a PR targeting a release branch is still
labeled against the latest rules, matching the original
`next-labeler-webhook` behavior.
## Security model
The action is designed to run under `pull_request_target` so it can label
PRs from forks, and is hardened accordingly:
- **No inputs.** The action reads `GITHUB_TOKEN` from the environment
rather than an input, so callers can't pass an unrelated higher-scoped
token from a fork-controlled context.
- **No PR-controlled code runs.** The calling workflow does not check out
the PR, install dependencies, or execute scripts from the PR. Only the
trusted action bundle, fetched by GitHub from `@canary`, runs.
- **No PR-controlled strings are shell-interpolated.** The only
PR-derived values are `pull_request.user.login` and the changed file
list — both returned by the GitHub API, not by the PR author — and
neither is ever passed to a shell.
- **Labels are capped by config.** The action only applies labels whose
names appear as keys in `src/config.json`. Anything else is rejected
before the `addLabels` call so a buggy config can't silently create new
labels in the repo.
## Config
Labeling rules live in [`src/config.json`](src/config.json). Each label
maps to a list of rules:
- A file glob (string) — matched with `minimatch` against the PR's
changed file paths.
- An author rule (`{ "type": "user", "pattern": "<login>" }`) — matched
case-insensitively against `pull_request.user.login`.
A label is applied if any of its rules match.
## Developing
After editing `src/*.ts` or `src/config.json`, rebuild the committed
bundle:
```bash
cd .github/actions/pr-auto-label
pnpm install
pnpm build
```
Commit the regenerated `dist/index.js` alongside your source change.
name: 'PR Auto-Labeler'
description: >-
Applies labels to a pull request based on changed files and author, using
the config in this action's src/config.json.
# This action deliberately has no inputs. It reads `GITHUB_TOKEN` from the
# environment, which the calling workflow must set via `env:` — typically
# to `${{ secrets.GITHUB_TOKEN }}`, the job's own token scoped by the
# workflow's `permissions:` block. Exposing a `github-token` input would
# let callers pass an unrelated (potentially higher-privileged) token from
# a fork-controlled context; forcing the use of the job token via `env:`
# keeps the principle of least privilege tied to the workflow's declared
# `permissions:` block.
runs:
using: 'node24'
main: 'dist/index.js'
This diff is collapsed.
This diff is collapsed.
{
"private": true,
"description": "Applies labels to a pull request based on changed files and author.",
"scripts": {
"build": "ncc build src/index.ts -m -o dist --license licenses.txt",
"types": "tsc --noEmit"
},
"dependencies": {
"@actions/core": "^1.11.1",
"@actions/github": "6.0.0",
"minimatch": "^9.0.9",
"typescript": "6.0.2"
},
"devDependencies": {
"@vercel/ncc": "^0.38.3"
}
}
......@@ -33,20 +33,6 @@
{ "type": "user", "pattern": "zackarychapple" },
{ "type": "user", "pattern": "zoolsher" }
],
"created-by: Chrome Aurora": [
{ "type": "user", "pattern": "atcastle" },
{ "type": "user", "pattern": "devknoll" },
{ "type": "user", "pattern": "housseindjirdeh" },
{ "type": "user", "pattern": "janicklas-ralph" },
{ "type": "user", "pattern": "kara" },
{ "type": "user", "pattern": "kyliau" },
{ "type": "user", "pattern": "spanicker" }
],
"CI approved": [
{ "type": "user", "pattern": "SukkaW" },
{ "type": "user", "pattern": "nextjs-bot" },
{ "type": "user", "pattern": "raunofreiberg" }
],
"created-by: Next.js team": [
{ "type": "user", "pattern": "acdlite" },
{ "type": "user", "pattern": "devjiwonchoi" },
......@@ -54,21 +40,12 @@
{ "type": "user", "pattern": "feedthejim" },
{ "type": "user", "pattern": "gaojude" },
{ "type": "user", "pattern": "gnoff" },
{ "type": "user", "pattern": "huozhi" },
{ "type": "user", "pattern": "ijjk" },
{ "type": "user", "pattern": "lubieowoce" },
{ "type": "user", "pattern": "samselikoff" },
{ "type": "user", "pattern": "shuding" },
{ "type": "user", "pattern": "styfle" },
{ "type": "user", "pattern": "unstubbable" },
{ "type": "user", "pattern": "ztanner" }
],
"created-by: Next.js DevEx team": [
{ "type": "user", "pattern": "ismaelrumzan" },
{ "type": "user", "pattern": "molebox" },
{ "type": "user", "pattern": "icyJoseph" },
{ "type": "user", "pattern": "aurorascharff" }
],
"created-by: Turbopack team": [
{ "type": "user", "pattern": "andrewimm" },
{ "type": "user", "pattern": "bgw" },
......
import { info, setFailed, warning } from '@actions/core'
import { context, getOctokit } from '@actions/github'
import { minimatch } from 'minimatch'
import config from './config.json'
type AuthorRule = { type: 'user'; pattern: string }
type LabelRule = string | AuthorRule
type LabelerConfig = { labels: Record<string, LabelRule[]> }
function isAuthorRule(rule: LabelRule): rule is AuthorRule {
return (
typeof rule === 'object' &&
rule !== null &&
'type' in rule &&
rule.type === 'user'
)
}
/**
* Compute the set of labels to apply for a pull request.
*/
export function computeLabels(
config: LabelerConfig,
author: string,
changedFiles: string[]
): string[] {
const matched = new Set<string>()
for (const [label, rules] of Object.entries(config.labels)) {
for (const rule of rules) {
if (isAuthorRule(rule)) {
if (rule.pattern.toLowerCase() === author.toLowerCase()) {
matched.add(label)
break
}
} else if (typeof rule === 'string') {
const matches = changedFiles.some((file) =>
minimatch(file, rule, { dot: true, matchBase: false })
)
if (matches) {
matched.add(label)
break
}
} else {
warning(
`Unknown rule type for label "${label}": ${JSON.stringify(rule)}`
)
}
}
}
return Array.from(matched)
}
async function main() {
// Read the token strictly from the environment so a caller can't pass an
// unrelated higher-privileged token via an action input.
const token = process.env.GITHUB_TOKEN
if (!token) {
throw new TypeError(
'GITHUB_TOKEN is not set. Ensure the calling workflow grants `pull-requests: write`.'
)
}
const pr = context.payload.pull_request
if (!pr) {
info('No pull_request payload present; skipping.')
return
}
const { owner, repo } = context.repo
const prNumber: number = pr.number
const author: string | undefined = pr.user?.login
if (!author) {
warning('Pull request has no author login; skipping.')
return
}
const octokit = getOctokit(token)
const changedFiles: string[] = await octokit.paginate(
octokit.rest.pulls.listFiles,
{ owner, repo, pull_number: prNumber, per_page: 100 },
(response) => response.data.map((f) => f.filename)
)
info(`PR #${prNumber} author: ${author}`)
info(`PR #${prNumber} changed files: ${changedFiles.length}`)
const allowedLabels = new Set(Object.keys((config as LabelerConfig).labels))
const labelsToAdd = computeLabels(
config as LabelerConfig,
author,
changedFiles
).filter((label) => {
// Defense in depth: `addLabels` will create missing labels on the fly,
// so ensure the set we send is always a subset of the config's keys.
// `computeLabels` already enforces this, but an explicit filter here
// keeps the invariant local to the API call.
if (!allowedLabels.has(label)) {
warning(`Skipping unknown label "${label}" not declared in config.`)
return false
}
return true
})
if (labelsToAdd.length === 0) {
info('No labels matched.')
return
}
info(`Applying labels: ${labelsToAdd.join(', ')}`)
try {
await octokit.rest.issues.addLabels({
owner,
repo,
issue_number: prNumber,
labels: labelsToAdd,
})
} catch (error) {
setFailed(
`Failed to apply labels to PR #${prNumber}: ${
error instanceof Error ? (error.stack ?? error.message) : String(error)
}`
)
}
}
main().catch((error) => {
setFailed(
error instanceof Error ? (error.stack ?? error.message) : String(error)
)
})
{
"compilerOptions": {
"target": "es2024",
"module": "preserve",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"rootDir": "./src",
"strict": true,
"skipLibCheck": false
},
"files": ["./src/index.ts"]
}
......@@ -6,7 +6,7 @@ inputs:
required: false
default: ''
turbo-token:
description: 'Fallback TURBO_TOKEN if not set in environment (e.g. from secrets.TURBO_REMOTE_CACHE_TOKEN)'
description: 'Fallback TURBO_TOKEN if not set in environment (e.g. from secrets.TURBO_TOKEN)'
required: false
default: ''
runs:
......
#!/usr/bin/env bash
set -euo pipefail
# Normalize TURBO_API and TURBO_TOKEN: prefer runner .bashrc values,
# Normalize TURBO_API and TURBO_TOKEN: prefer environment values and
# fall back to Vercel's public API and the secret passed as an action input.
if [ -z "${TURBO_API:-}" ]; then
export TURBO_API="https://api.vercel.com"
......@@ -18,7 +18,7 @@ if [ -z "${TURBO_TOKEN:-}" ]; then
fi
if [ -z "${TURBO_TEAM:-}" ]; then
export TURBO_TEAM="vercel"
export TURBO_TEAM="vtest314-next-adapter-e2e-tests"
echo "TURBO_TEAM=${TURBO_TEAM}" >> "$GITHUB_ENV"
fi
......
......@@ -3,6 +3,7 @@ lockfileVersion: '9.0'
settings:
autoInstallPeers: true
excludeLinksFromLockfile: false
injectWorkspacePackages: true
importers:
......@@ -75,7 +76,7 @@ importers:
version: 7.8.0
ai:
specifier: ^3.4.14
version: 3.4.33(react@19.0.0)(sswr@2.2.0(svelte@5.46.1))(svelte@5.46.1)(vue@3.5.26(typescript@5.7.2))(zod@3.25.76)
version: 3.4.33(react@19.0.0)(sswr@2.2.0(svelte@5.46.1))(svelte@5.46.1)(vue@3.5.26(typescript@6.0.2))(zod@3.25.76)
slack-block-builder:
specifier: ^2.8.0
version: 2.8.0
......@@ -130,6 +131,25 @@ importers:
specifier: 5.1.6
version: 5.1.6
actions/pr-auto-label:
dependencies:
'@actions/core':
specifier: ^1.11.1
version: 1.11.1
'@actions/github':
specifier: 6.0.0
version: 6.0.0
minimatch:
specifier: ^9.0.9
version: 9.0.9
typescript:
specifier: 6.0.2
version: 6.0.2
devDependencies:
'@vercel/ncc':
specifier: ^0.38.3
version: 0.38.3
actions/upload-turboyet-data:
dependencies:
'@vercel/kv':
......@@ -197,9 +217,6 @@ packages:
'@actions/github@6.0.0':
resolution: {integrity: sha512-alScpSVnYmjNEXboZjarjukQEzgCRmjMv6Xj47fsdnqGS73bjJNDpiiXmp8jr0UZLdUB6d9jW63IcmddUP+l0g==}
'@actions/http-client@2.2.0':
resolution: {integrity: sha512-q+epW0trjVUUHboliPb4UF9g2msf+w61b32tAkFEwL/IwP0DQWgbCMM0Hbe3e3WXSKz5VcUXbzJQgy8Hkra/Lg==}
'@actions/http-client@2.2.3':
resolution: {integrity: sha512-mx8hyJi/hjFvbPokCg4uRd4ZX78t+YyRPtnKWwIl+RzNaVuFpQHfmlGVfsKEJN8LwTCvL+DfVgAM04XaHkm6bA==}
......@@ -303,10 +320,6 @@ packages:
resolution: {integrity: sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==}
engines: {node: '>=6.9.0'}
'@fastify/busboy@2.1.0':
resolution: {integrity: sha512-+KpH+QxZU7O4675t3mnkQKcZZg56u+K/Ct2K+N2AZYNVK8kyeo/bI18tI8aPm3tvNNRyTWfj6s5tnGNlcbQRsA==}
engines: {node: '>=14'}
'@fastify/busboy@2.1.1':
resolution: {integrity: sha512-vBZP4NlzfOlerQTnba4aqZoMhE/a9HY7HRqoOPaETQcSQuWEIyZMHGfVu6w9wGtGK5fED5qRs2DteVCjOH60sA==}
engines: {node: '>=14'}
......@@ -559,6 +572,9 @@ packages:
brace-expansion@1.1.12:
resolution: {integrity: sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==}
brace-expansion@2.1.0:
resolution: {integrity: sha512-TN1kCZAgdgweJhWWpgKYrQaMNHcDULHkWwQIspdtjV4Y5aurRdZpjAqn6yX3FPqTA9ngHCc4hJxMAMgGfve85w==}
ccount@1.1.0:
resolution: {integrity: sha512-vlNK021QdI7PNeiUh/lKkC/mNHHfV0m/Ad5JoI0TYtlBnJAslM/JIkm/tGC88bkLIwO6OQ5uV6ztS6kVAtCDlg==}
......@@ -854,6 +870,10 @@ packages:
minimatch@3.1.2:
resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==}
minimatch@9.0.9:
resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==}
engines: {node: '>=16 || 14 >=14.17'}
nanoid@3.3.11:
resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==}
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
......@@ -1119,18 +1139,14 @@ packages:
engines: {node: '>=14.17'}
hasBin: true
typescript@5.7.2:
resolution: {integrity: sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==}
typescript@6.0.2:
resolution: {integrity: sha512-bGdAIrZ0wiGDo5l8c++HWtbaNCWTS4UTv7RaTH/ThVIgjkveJt83m74bBHMJkuCbslY8ixgLBVZJIOiQlQTjfQ==}
engines: {node: '>=14.17'}
hasBin: true
undici-types@5.26.5:
resolution: {integrity: sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==}
undici@5.28.2:
resolution: {integrity: sha512-wh1pHJHnUeQV5Xa8/kyQhO7WFa8M34l026L5P/+2TYiakvGy5Rdc8jWZVyG7ieht/0WgJLEd3kcU5gKx+6GC8w==}
engines: {node: '>=14.0'}
undici@5.28.4:
resolution: {integrity: sha512-72RFADWFqKmUb2hmmvNODKL3p9hcB6Gt2DOQMis1SEBaV6a4MH8soBvzg+95CYhCKPFedut2JY9bMfrDl9D23g==}
engines: {node: '>=14.0'}
......@@ -1271,16 +1287,11 @@ snapshots:
'@actions/github@6.0.0':
dependencies:
'@actions/http-client': 2.2.0
'@actions/http-client': 2.2.3
'@octokit/core': 5.0.2
'@octokit/plugin-paginate-rest': 9.1.5(@octokit/core@5.0.2)
'@octokit/plugin-rest-endpoint-methods': 10.2.0(@octokit/core@5.0.2)
'@actions/http-client@2.2.0':
dependencies:
tunnel: 0.0.6
undici: 5.28.2
'@actions/http-client@2.2.3':
dependencies:
tunnel: 0.0.6
......@@ -1357,13 +1368,13 @@ snapshots:
optionalDependencies:
zod: 3.25.76
'@ai-sdk/vue@0.0.59(vue@3.5.26(typescript@5.7.2))(zod@3.25.76)':
'@ai-sdk/vue@0.0.59(vue@3.5.26(typescript@6.0.2))(zod@3.25.76)':
dependencies:
'@ai-sdk/provider-utils': 1.0.22(zod@3.25.76)
'@ai-sdk/ui-utils': 0.0.50(zod@3.25.76)
swrv: 1.1.0(vue@3.5.26(typescript@5.7.2))
swrv: 1.1.0(vue@3.5.26(typescript@6.0.2))
optionalDependencies:
vue: 3.5.26(typescript@5.7.2)
vue: 3.5.26(typescript@6.0.2)
transitivePeerDependencies:
- zod
......@@ -1380,8 +1391,6 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
'@fastify/busboy@2.1.0': {}
'@fastify/busboy@2.1.1': {}
'@jridgewell/gen-mapping@0.3.13':
......@@ -1630,17 +1639,17 @@ snapshots:
'@vue/shared': 3.5.26
csstype: 3.2.3
'@vue/server-renderer@3.5.26(vue@3.5.26(typescript@5.7.2))':
'@vue/server-renderer@3.5.26(vue@3.5.26(typescript@6.0.2))':
dependencies:
'@vue/compiler-ssr': 3.5.26
'@vue/shared': 3.5.26
vue: 3.5.26(typescript@5.7.2)
vue: 3.5.26(typescript@6.0.2)
'@vue/shared@3.5.26': {}
acorn@8.15.0: {}
ai@3.4.33(react@19.0.0)(sswr@2.2.0(svelte@5.46.1))(svelte@5.46.1)(vue@3.5.26(typescript@5.7.2))(zod@3.25.76):
ai@3.4.33(react@19.0.0)(sswr@2.2.0(svelte@5.46.1))(svelte@5.46.1)(vue@3.5.26(typescript@6.0.2))(zod@3.25.76):
dependencies:
'@ai-sdk/provider': 0.0.26
'@ai-sdk/provider-utils': 1.0.22(zod@3.25.76)
......@@ -1648,7 +1657,7 @@ snapshots:
'@ai-sdk/solid': 0.0.54(zod@3.25.76)
'@ai-sdk/svelte': 0.0.57(svelte@5.46.1)(zod@3.25.76)
'@ai-sdk/ui-utils': 0.0.50(zod@3.25.76)
'@ai-sdk/vue': 0.0.59(vue@3.5.26(typescript@5.7.2))(zod@3.25.76)
'@ai-sdk/vue': 0.0.59(vue@3.5.26(typescript@6.0.2))(zod@3.25.76)
'@opentelemetry/api': 1.9.0
eventsource-parser: 1.1.2
json-schema: 0.4.0
......@@ -1697,6 +1706,10 @@ snapshots:
balanced-match: 1.0.2
concat-map: 0.0.1
brace-expansion@2.1.0:
dependencies:
balanced-match: 1.0.2
ccount@1.1.0: {}
chalk@5.3.0: {}
......@@ -1991,6 +2004,10 @@ snapshots:
dependencies:
brace-expansion: 1.1.12
minimatch@9.0.9:
dependencies:
brace-expansion: 2.1.0
nanoid@3.3.11: {}
nanoid@3.3.6: {}
......@@ -2199,9 +2216,9 @@ snapshots:
swrev@4.0.0: {}
swrv@1.1.0(vue@3.5.26(typescript@5.7.2)):
swrv@1.1.0(vue@3.5.26(typescript@6.0.2)):
dependencies:
vue: 3.5.26(typescript@5.7.2)
vue: 3.5.26(typescript@6.0.2)
throttleit@2.1.0: {}
......@@ -2221,15 +2238,10 @@ snapshots:
typescript@5.1.6: {}
typescript@5.7.2:
optional: true
typescript@6.0.2: {}
undici-types@5.26.5: {}
undici@5.28.2:
dependencies:
'@fastify/busboy': 2.1.0
undici@5.28.4:
dependencies:
'@fastify/busboy': 2.1.1
......@@ -2309,15 +2321,15 @@ snapshots:
unist-util-stringify-position: 2.0.3
vfile-message: 2.0.4
vue@3.5.26(typescript@5.7.2):
vue@3.5.26(typescript@6.0.2):
dependencies:
'@vue/compiler-dom': 3.5.26
'@vue/compiler-sfc': 3.5.26
'@vue/runtime-dom': 3.5.26
'@vue/server-renderer': 3.5.26(vue@3.5.26(typescript@5.7.2))
'@vue/server-renderer': 3.5.26(vue@3.5.26(typescript@6.0.2))
'@vue/shared': 3.5.26
optionalDependencies:
typescript: 5.7.2
typescript: 6.0.2
web-namespaces@1.1.4: {}
......
......@@ -24,6 +24,12 @@ Choose the right checklist for the change(s) that you're making:
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md
### Signed commits
- This repository requires verified commit signatures on protected branches.
- If this pull request is blocked for unsigned commits, re-sign the commits and force-push the branch.
- A `Signed-off-by` line in the commit message is not enough.
## For Maintainers
......
......@@ -24,8 +24,11 @@ env:
# TODO: we should add the relevant envs later to to switch to strict mode
TURBO_ARGS: '-v --env-mode loose --remote-cache-timeout 90 --summarize --log-order stream'
NODE_LTS_VERSION: 20
TURBO_TEAM: 'vercel'
TURBO_CACHE: 'remote:rw'
TURBO_TEAM: 'vtest314-next-adapter-e2e-tests'
# Prefer shared remote cache across runs, but keep local cache enabled so jobs
# degrade gracefully if the remote cache or token is unavailable.
TURBO_CACHE: 'local:rw,remote:rw'
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
# Without this environment variable, rust-lld will fail because some dependencies defaults to newer version of macOS by default.
#
# See https://doc.rust-lang.org/rustc/platform-support/apple-darwin.html#os-version for more details
......@@ -180,12 +183,12 @@ jobs:
build_task: build-native-release
os:
mac:
host: "['self-hosted', 'macos', 'arm64']"
arch: [x86_64, aarch64]
host: "['macos-15']"
vendor: apple
sys: darwin
arch: [x86_64, aarch64]
windows:
host: "['self-hosted', 'windows', 'x64']"
host: "['windows-latest-8-core-oss']"
vendor: pc
sys: windows
abi: msvc
......@@ -193,7 +196,7 @@ jobs:
x86_64: {}
aarch64: {}
linux:
host: "['self-hosted', 'linux', 'x64', 'metal']"
host: "['ubuntu-latest-16-core-oss']"
docker: next-swc-builder:latest
vendor: unknown
sys: linux
......@@ -246,10 +249,12 @@ jobs:
node-version: ${{ env.NODE_LTS_VERSION }}
check-latest: true
- name: Prepare corepack
if: ${{ matrix.os != 'windows' }}
run: npm i -g corepack@0.31
- name: Setup corepack
run: |
npm i -g corepack@0.31
corepack enable
run: corepack enable
# we always want to run this to set environment variables
# (skip for docker builds - rust is already in the image)
......@@ -295,7 +300,7 @@ jobs:
docker run --rm \
-e CI -e RUST_BACKTRACE -e CARGO_TERM_COLOR \
-e CARGO_INCREMENTAL=0 -e CARGO_REGISTRIES_CRATES_IO_PROTOCOL \
${{ env.NEXT_SKIP_BUILD_CACHE && ' ' || '-e TURBO_API -e TURBO_TEAM -e TURBO_TOKEN -e TURBO_VERSION -e TURBO_CACHE=remote:rw' }} \
${{ env.NEXT_SKIP_BUILD_CACHE && ' ' || '-e TURBO_API -e TURBO_TEAM -e TURBO_TOKEN -e TURBO_VERSION -e TURBO_CACHE=local:rw,remote:rw' }} \
-e TARGET="${{ matrix.target }}" \
-e ABI="${{ matrix.abi }}" \
-e ARCH="${{ matrix.arch }}" \
......@@ -386,11 +391,7 @@ jobs:
matrix:
target: [web, nodejs]
runs-on:
- 'self-hosted'
- 'linux'
- 'x64'
- 'metal'
runs-on: ubuntu-latest-16-core-oss
steps:
- uses: actions/checkout@v6
......@@ -544,10 +545,20 @@ jobs:
merge-multiple: true
path: crates/wasm
- name: Create GitHub App token
id: release-app-token
uses: actions/create-github-app-token@v3
with:
client-id: ${{ vars.RELEASE_GITHUB_APP_CLIENT_ID }}
private-key: ${{ secrets.RELEASE_GITHUB_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: next.js
permission-contents: write
- run: ./scripts/publish-native.js
- run: ./scripts/publish-release.js
env:
RELEASE_BOT_GITHUB_TOKEN: ${{ secrets.RELEASE_BOT_GITHUB_TOKEN }}
RELEASE_GITHUB_TOKEN: ${{ steps.release-app-token.outputs.token }}
buildPassed:
needs: ['deploy-target', 'build', 'build-wasm', 'build-native']
......@@ -580,9 +591,11 @@ jobs:
path: turbopack-bin-size
- name: Install datadog-ci
if: ${{ env.DATADOG_API_KEY != '' }}
uses: ./.github/actions/setup-datadog-ci
- name: Upload to Datadog
if: ${{ env.DATADOG_API_KEY != '' }}
run: |
ls -al turbopack-bin-size
......
......@@ -63,6 +63,50 @@ jobs:
)
}}
pr-ci-metadata:
name: Upload PR CI metadata
if: ${{ github.event_name == 'pull_request' }}
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Write PR metadata
env:
PR_NUMBER: ${{ github.event.pull_request.number }}
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
PR_HEAD_REF: ${{ github.event.pull_request.head.ref }}
PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
PR_IS_FORK: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
run: |
mkdir -p pr-ci-metadata
node <<'NODE'
const fs = require('fs')
fs.writeFileSync(
'pr-ci-metadata/pr.json',
JSON.stringify(
{
number: Number(process.env.PR_NUMBER),
headSha: process.env.PR_HEAD_SHA,
headRef: process.env.PR_HEAD_REF,
headRepo: process.env.PR_HEAD_REPO,
baseRef: process.env.PR_BASE_REF,
isFork: process.env.PR_IS_FORK === 'true',
},
null,
2
)
)
NODE
- name: Upload PR metadata
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: pr-ci-metadata
path: pr-ci-metadata/pr.json
retention-days: 1
build-native:
name: build-native
uses: ./.github/workflows/build_reusable.yml
......@@ -82,7 +126,7 @@ jobs:
with:
skipInstallBuild: 'yes'
stepName: 'build-native-windows'
runs_on_labels: '["windows","self-hosted","x64"]'
runs_on_labels: '["windows-latest-8-core-oss"]'
buildNativeTarget: 'x86_64-pc-windows-msvc'
uploadNativeArtifact: 'next-swc-windows'
......@@ -194,6 +238,7 @@ jobs:
needsRust: 'yes'
needsNextest: 'yes'
skipNativeBuild: 'yes'
skipInstallBuild: 'yes'
afterBuild: pnpm dlx turbo@${TURBO_VERSION} run test-cargo-unit ${TURBO_ARGS}
stepName: 'test-cargo-unit'
secrets: inherit
......@@ -713,7 +758,7 @@ jobs:
nodeVersion: ${{ matrix.node }}
afterBuild: node run-tests.js --type unit
stepName: 'test-unit-windows-${{ matrix.node }}'
runs_on_labels: '["windows","self-hosted","x64"]'
runs_on_labels: '["windows-latest-8-core-oss"]'
buildNativeTarget: 'x86_64-pc-windows-msvc'
secrets: inherit
......@@ -885,7 +930,7 @@ jobs:
test/e2e/app-dir/proxy-runtime-nodejs/proxy-runtime-nodejs.test.ts \
test/development/app-dir/segment-explorer/segment-explorer.test.ts
stepName: 'test-dev-windows'
runs_on_labels: '["windows","self-hosted","x64"]'
runs_on_labels: '["windows-latest-8-core-oss"]'
buildNativeTarget: 'x86_64-pc-windows-msvc'
secrets: inherit
......@@ -908,7 +953,7 @@ jobs:
test/integration/create-next-app/index.test.ts \
test/integration/create-next-app/package-manager/pnpm.test.ts
stepName: 'test-integration-windows'
runs_on_labels: '["windows","self-hosted","x64"]'
runs_on_labels: '["windows-latest-8-core-oss"]'
buildNativeTarget: 'x86_64-pc-windows-msvc'
secrets: inherit
......@@ -931,7 +976,7 @@ jobs:
test/e2e/app-dir/non-root-project-monorepo/non-root-project-monorepo.test.ts \
test/e2e/app-dir/proxy-runtime-nodejs/proxy-runtime-nodejs.test.ts
stepName: 'test-prod-windows'
runs_on_labels: '["windows","self-hosted","x64"]'
runs_on_labels: '["windows-latest-8-core-oss"]'
buildNativeTarget: 'x86_64-pc-windows-msvc'
secrets: inherit
......
......@@ -62,7 +62,7 @@ on:
description: 'List of runner labels'
required: false
type: string
default: '["self-hosted", "linux", "x64", "metal"]'
default: '["ubuntu-latest-16-core-oss"]'
buildNativeTarget:
description: 'Target for build-native step'
required: false
......@@ -107,8 +107,11 @@ env:
# disable backtrace for test snapshots
RUST_BACKTRACE: 0
TURBO_TEAM: 'vtest314-next-e2e-tests'
TURBO_CACHE: 'remote:rw'
TURBO_TEAM: 'vtest314-next-adapter-e2e-tests'
# Prefer shared remote cache across runs, but keep local cache enabled so jobs
# degrade gracefully if the remote cache or token is unavailable.
TURBO_CACHE: 'local:rw,remote:rw'
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
NEXT_TELEMETRY_DISABLED: 1
# allow not skipping install-native postinstall script if we don't have a binary available already
......@@ -152,7 +155,7 @@ jobs:
steps:
# enforce consistent line endings for git on windows
- name: Configure git to use LF endings
if: ${{ contains(fromJson(inputs.runs_on_labels), 'windows') }}
if: ${{ runner.os == 'Windows' }}
run: |
git config --global core.autocrlf false
git config --global core.eol lf
......@@ -172,9 +175,10 @@ jobs:
- name: Install fnm
if: steps.check-fnm.outputs.found != 'true'
run: |
export FNM_DIR="${HOME}/.local/share/fnm"
curl -fsSL https://fnm.vercel.app/install | bash
export PATH="/home/runner/.local/share/fnm:$PATH"
echo "/home/runner/.local/share/fnm" >> $GITHUB_PATH
export PATH="$FNM_DIR:$PATH"
echo "$FNM_DIR" >> $GITHUB_PATH
fnm env --json | jq -r 'to_entries|map("\(.key)=\(.value|tostring)")|.[]' | xargs -I {} echo "{}" >> $GITHUB_ENV
- name: Normalize input step names into path key
......@@ -207,7 +211,7 @@ jobs:
which node
node --version
- name: Prepare corepack
if: ${{ contains(fromJson(inputs.runs_on_labels), 'ubuntu-latest') }}
if: ${{ runner.os == 'Linux' }}
run: |
npm i -g corepack@0.31
- run: corepack enable
......@@ -271,7 +275,7 @@ jobs:
uses: ./.github/actions/sccache
if: ${{ runner.os != 'Windows' && ((inputs.uploadNativeArtifact != '') || inputs.needsNextest == 'yes' || inputs.needsRust == 'yes') }}
with:
turbo-token: ${{ secrets.TURBO_REMOTE_CACHE_TOKEN }}
turbo-token: ${{ secrets.TURBO_TOKEN }}
- name: Download pre-built native binary
if: ${{ inputs.skipNativeBuild != 'yes' && inputs.uploadNativeArtifact == '' }}
......@@ -279,7 +283,7 @@ jobs:
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: ${{ contains(fromJson(inputs.runs_on_labels), 'windows') && 'next-swc-windows' || 'next-swc-linux' }}
name: ${{ runner.os == 'Windows' && 'next-swc-windows' || 'next-swc-linux' }}
path: packages/next-swc/native/
- run: pnpm dlx turbo@${TURBO_VERSION} run build-native-${{ inputs.rustBuildProfile }} ${TURBO_ARGS} --summarize -- --target ${{ inputs.buildNativeTarget }}
......@@ -305,7 +309,7 @@ jobs:
if: ${{ inputs.skipInstallBuild != 'yes' }}
- run: pnpm install
if: ${{ inputs.skipInstallBuild != 'yes' }}
if: ${{ inputs.skipInstallBuild != 'yes' || inputs.needsNextest == 'yes' }}
- name: Install node-file-trace test dependencies
if: ${{ inputs.needsNextest == 'yes' }}
......@@ -398,11 +402,11 @@ jobs:
path: packages/next/dist/compiled/next-server/report.*.html
- name: Install datadog-ci
if: ${{ inputs.afterBuild && always() && !github.event.pull_request.head.repo.fork }}
if: ${{ inputs.afterBuild && always() && !github.event.pull_request.head.repo.fork && env.DATADOG_API_KEY != '' }}
uses: ./.github/actions/setup-datadog-ci
- name: Upload test report to datadog
if: ${{ inputs.afterBuild && always() && !github.event.pull_request.head.repo.fork }}
if: ${{ inputs.afterBuild && always() && !github.event.pull_request.head.repo.fork && env.DATADOG_API_KEY != '' }}
run: |
# Add a `test.type` tag to distinguish between turbopack and next.js runs
# Add a `nextjs.test_session.name` tag to help identify the job
......
......@@ -11,10 +11,6 @@ on:
type: string
required: true
secrets:
RELEASE_BOT_GITHUB_TOKEN:
required: true
name: Create Release Branch
env:
......@@ -39,13 +35,33 @@ jobs:
node-version: 20
check-latest: true
- name: Create GitHub App token
id: release-app-token
uses: actions/create-github-app-token@v3
with:
client-id: ${{ vars.RELEASE_GITHUB_APP_CLIENT_ID }}
private-key: ${{ secrets.RELEASE_GITHUB_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: next.js
permission-contents: write
permission-environments: write
permission-workflows: write
- name: Get GitHub App user ID
id: release-app-user
run: |
user_id="$(gh api "/users/${{ steps.release-app-token.outputs.app-slug }}[bot]" --jq .id)"
echo "user-id=$user_id" >> "$GITHUB_OUTPUT"
env:
GH_TOKEN: ${{ steps.release-app-token.outputs.token }}
- name: Clone Next.js repository
run: git clone https://github.com/vercel/next.js.git --depth=25 --single-branch --branch ${GITHUB_REF_NAME:-canary} .
- name: Check token
run: gh auth status
env:
GITHUB_TOKEN: ${{ secrets.RELEASE_BOT_GITHUB_TOKEN }}
GH_TOKEN: ${{ steps.release-app-token.outputs.token }}
# https://github.com/actions/virtual-environments/issues/1187
- name: tune linux network
......@@ -72,6 +88,8 @@ jobs:
- run: node ./scripts/create-release-branch.js --branch-name "${INPUT_BRANCHNAME}" --tag-name "${INPUT_TAGNAME}"
env:
RELEASE_BOT_GITHUB_TOKEN: ${{ secrets.RELEASE_BOT_GITHUB_TOKEN }}
RELEASE_GITHUB_TOKEN: ${{ steps.release-app-token.outputs.token }}
RELEASE_GITHUB_APP_SLUG: ${{ steps.release-app-token.outputs.app-slug }}
RELEASE_GITHUB_APP_USER_ID: ${{ steps.release-app-user.outputs.user-id }}
INPUT_BRANCHNAME: ${{ github.event.inputs.branchName }}
INPUT_TAGNAME: ${{ github.event.inputs.tagName }}
......@@ -56,7 +56,7 @@ jobs:
secrets: inherit
generate-matrices:
runs-on: [self-hosted, linux, x64, metal]
runs-on: ubuntu-latest-16-core-oss
steps:
- id: out
run: |
......@@ -147,7 +147,7 @@ jobs:
collect_nextjs_development_integration_stat:
needs: [test-e2e, test-integration]
name: Next.js integration test development status report
runs-on: [self-hosted, linux, x64, metal]
runs-on: ubuntu-latest-16-core-oss
if: always()
permissions:
pull-requests: write
......
name: PR CI Comment
on:
workflow_run:
workflows: ['build-and-test', 'Generate Stats']
types: [completed]
permissions:
actions: read
contents: read
pull-requests: write
jobs:
comment:
name: Comment on PR
if: ${{ github.event.workflow_run.event == 'pull_request' && github.repository == 'vercel/next.js' }}
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- name: Download PR metadata
continue-on-error: true
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: pr-ci-metadata
path: pr-ci-metadata
run-id: ${{ github.event.workflow_run.id }}
github-token: ${{ secrets.GITHUB_TOKEN }}
- name: Comment on PR
run: node scripts/pr-ci-comment.mjs
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
name: Pull Request Auto-Labeler
# Runs on pull_request_target so the workflow has the permissions of the
# base repository and can write labels on PRs opened from forks.
#
# `pull_request_target` is only risky when a workflow holding a
# write-scoped token also executes PR-controlled content — e.g. checking
# out the PR head and running its build/install scripts, or interpolating
# PR text (titles, bodies, branch names) directly into shell commands.
# This workflow does neither:
#
# 1. The action is referenced as `vercel/next.js/.github/actions/
# pr-auto-label@canary`, so GitHub Actions fetches the action bundle
# (with the labeler config inlined into it at build time) directly
# from the `canary` ref of this repo — independent of the PR's
# source or target branch. A fork PR cannot influence which code
# runs here. Pinning to `canary` (rather than the PR's base ref)
# also preserves the original `next-labeler-webhook` semantics:
# PRs targeting release branches are still labeled using the
# current canary rules.
# 2. No PR-controlled code executes on the runner. We don't check out
# the PR, run `pnpm install` / `npm install`, or execute any script
# defined by the PR's `package.json`.
# 3. No PR-controlled text is interpolated into `run:` scripts. The
# action reads `pull_request.user.login` and the list of changed
# files via the GitHub API — both authenticated by GitHub and not
# forgeable by the PR author — and passes them to the `octokit`
# client, not to a shell.
# 4. `permissions` is scoped to the minimum needed: `pull-requests:
# write` to apply labels.
# 5. `if: github.repository_owner == 'vercel'` prevents the workflow
# from running in unrelated forks of this repo.
#
# If you ever change this workflow to check out the PR head, install
# dependencies from the PR, or interpolate PR-provided strings into a
# shell command, revisit this threat model.
on:
pull_request_target:
# `opened` covers new PRs (including drafts) and `synchronize` covers
# every subsequent push. Other lifecycle events (`reopened`,
# `ready_for_review`, `edited`) don't change the file list or the
# author, so there's nothing new to label.
types: [opened, synchronize]
# Deny-by-default at the workflow level. The job below opts back in to
# `pull-requests: write` — the minimum needed to apply labels.
permissions: {}
concurrency:
# `github.event.pull_request.number` is always set for
# `pull_request_target`, but fall back to the run ID if this workflow is
# ever extended to run on other events, to avoid collapsing unrelated
# runs into the same group.
group: pr-auto-label-${{ github.event.pull_request.number || github.run_id }}
cancel-in-progress: true
jobs:
label:
if: github.repository_owner == 'vercel'
runs-on: ubuntu-latest
permissions:
# To add labels
pull-requests: write
steps:
- uses: vercel/next.js/.github/actions/pr-auto-label@canary
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
......@@ -18,8 +18,11 @@ env:
NODE_LTS_VERSION: 20
TEST_CONCURRENCY: 6
TURBO_TEAM: 'vercel'
TURBO_CACHE: 'remote:rw'
TURBO_TEAM: 'vtest314-next-adapter-e2e-tests'
# Prefer shared remote cache across runs, but keep local cache enabled so jobs
# degrade gracefully if the remote cache or token is unavailable.
TURBO_CACHE: 'local:rw,remote:rw'
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
NEXT_TELEMETRY_DISABLED: 1
# we build a dev binary for use in CI so skip downloading
# canary next-swc binaries in the monorepo
......@@ -31,6 +34,50 @@ env:
NEXT_DISABLE_SWC_WASM: 1
jobs:
pr-ci-metadata:
name: Upload PR CI metadata
if: ${{ github.event_name == 'pull_request' }}
runs-on: ubuntu-latest
permissions:
contents: read
steps:
- name: Write PR metadata
env:
PR_NUMBER: ${{ github.event.pull_request.number }}
PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}
PR_HEAD_REF: ${{ github.event.pull_request.head.ref }}
PR_HEAD_REPO: ${{ github.event.pull_request.head.repo.full_name }}
PR_BASE_REF: ${{ github.event.pull_request.base.ref }}
PR_IS_FORK: ${{ github.event.pull_request.head.repo.full_name != github.repository }}
run: |
mkdir -p pr-ci-metadata
node <<'NODE'
const fs = require('fs')
fs.writeFileSync(
'pr-ci-metadata/pr.json',
JSON.stringify(
{
number: Number(process.env.PR_NUMBER),
headSha: process.env.PR_HEAD_SHA,
headRef: process.env.PR_HEAD_REF,
headRepo: process.env.PR_HEAD_REPO,
baseRef: process.env.PR_BASE_REF,
isFork: process.env.PR_IS_FORK === 'true',
},
null,
2
)
)
NODE
- name: Upload PR metadata
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: pr-ci-metadata
path: pr-ci-metadata/pr.json
retention-days: 1
build:
uses: ./.github/workflows/build_reusable.yml
secrets: inherit
......@@ -47,11 +94,7 @@ jobs:
fail-fast: false
matrix:
bundler: [webpack, turbopack]
runs-on:
- 'self-hosted'
- 'linux'
- 'x64'
- 'metal'
runs-on: ubuntu-latest-16-core-oss
steps:
- uses: actions/checkout@v4
with:
......@@ -75,7 +118,6 @@ jobs:
with:
bundler: ${{ matrix.bundler }}
env:
PR_STATS_COMMENT_TOKEN: ${{ secrets.PR_STATS_COMMENT_TOKEN }}
TURBO_TEAM: ${{ env.TURBO_TEAM }}
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
TURBO_CACHE: ${{ env.TURBO_CACHE }}
......@@ -126,6 +168,5 @@ jobs:
working-directory: .github/actions/next-stats-action
run: node src/aggregate-results.js ${{ github.workspace }}/stats-results
env:
PR_STATS_COMMENT_TOKEN: ${{ secrets.PR_STATS_COMMENT_TOKEN }}
KV_REST_API_URL: ${{ secrets.KV_REST_API_URL }}
KV_REST_API_TOKEN: ${{ secrets.KV_REST_API_TOKEN }}
......@@ -16,11 +16,7 @@ on:
jobs:
build_nextjs:
name: Build Next.js for the turbopack integration test
runs-on:
- 'self-hosted'
- 'linux'
- 'x64'
- 'metal'
runs-on: ubuntu-latest-16-core-oss
outputs:
output1: ${{ steps.build-next-swc-turbopack-patch.outputs.success }}
steps:
......
......@@ -84,11 +84,23 @@ jobs:
if: steps.precheck.outputs.should_evaluate == 'true'
run: pnpm install --frozen-lockfile --ignore-scripts
- name: Create GitHub App token
id: release-app-token
if: steps.precheck.outputs.should_evaluate == 'true'
uses: actions/create-github-app-token@v3
with:
client-id: ${{ vars.RELEASE_GITHUB_APP_CLIENT_ID }}
private-key: ${{ secrets.RELEASE_GITHUB_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: next.js
permission-actions: read
permission-contents: read
- name: Evaluate backport release
id: evaluate
if: steps.precheck.outputs.should_evaluate == 'true'
env:
RELEASE_BOT_GITHUB_TOKEN: ${{ secrets.RELEASE_BOT_GITHUB_TOKEN }}
RELEASE_GITHUB_TOKEN: ${{ steps.release-app-token.outputs.token }}
WORKFLOW_RUN_ID: ${{ github.event_name == 'workflow_dispatch' && inputs.workflowRunId || github.event.workflow_run.id }}
HEAD_SHA: ${{ github.event_name == 'workflow_dispatch' && inputs.headSha || github.event.workflow_run.head_sha }}
HEAD_COMMIT_MESSAGE: ${{ github.event_name == 'workflow_dispatch' && '' || github.event.workflow_run.head_commit.message }}
......@@ -108,9 +120,19 @@ jobs:
if: ${{ needs.evaluate.outputs.should_dispatch == 'true' && ((github.event_name == 'workflow_dispatch' && inputs.dispatch) || (github.event_name == 'workflow_run' && vars.ENABLE_BACKPORT_CANARY_SYNC == 'true')) }}
runs-on: ubuntu-latest
steps:
- name: Create GitHub App token
id: release-app-token
uses: actions/create-github-app-token@v3
with:
client-id: ${{ vars.RELEASE_GITHUB_APP_CLIENT_ID }}
private-key: ${{ secrets.RELEASE_GITHUB_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: next.js
permission-actions: write
- uses: actions/github-script@v7
with:
github-token: ${{ secrets.RELEASE_BOT_GITHUB_TOKEN }}
github-token: ${{ steps.release-app-token.outputs.token }}
script: |
await github.request(
"POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches",
......
......@@ -4,7 +4,7 @@ on:
inputs:
runner:
type: string
default: '["self-hosted", "linux", "x64", "metal"]'
default: '["ubuntu-latest-16-core-oss"]'
os:
type: string
default: 'linux'
......@@ -16,6 +16,8 @@ env:
TURBOPACK_BENCH_COUNTS: '100'
TURBOPACK_BENCH_PROGRESS: '1'
NODE_LTS_VERSION: 20
TURBO_TEAM: 'vtest314-next-adapter-e2e-tests'
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
jobs:
test:
......@@ -48,7 +50,7 @@ jobs:
- name: Start sccache
uses: ./.github/actions/sccache
with:
turbo-token: ${{ secrets.TURBO_REMOTE_CACHE_TOKEN }}
turbo-token: ${{ secrets.TURBO_TOKEN }}
- name: Build benchmarks for tests
timeout-minutes: 120
......
......@@ -245,9 +245,11 @@ jobs:
merge-multiple: true
- name: Install datadog-ci
if: ${{ env.DATADOG_API_KEY != '' }}
uses: ./.github/actions/setup-datadog-ci
- name: Upload test report to datadog
if: ${{ env.DATADOG_API_KEY != '' }}
run: |
if [ -d ./test/test-junit-report ]; then
DD_ENV=ci "$DATADOG_CI_PATH" junit upload --tags test.type:deploy --service nextjs ./test/test-junit-report
......
......@@ -13,8 +13,11 @@ env:
VERCEL_ADAPTER_TEST_TEAM: vtest314-next-adapter-e2e-tests
VERCEL_ADAPTER_TEST_TOKEN: ${{ secrets.VERCEL_ADAPTER_TEST_TOKEN }}
NODE_LTS_VERSION: 20
TURBO_TEAM: 'vercel'
TURBO_CACHE: 'remote:rw'
TURBO_TEAM: 'vtest314-next-adapter-e2e-tests'
# Prefer shared remote cache across runs, but keep local cache enabled so jobs
# degrade gracefully if the remote cache or token is unavailable.
TURBO_CACHE: 'local:rw,remote:rw'
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
run-name: test-e2e-project-reset (scheduled)
......
......@@ -52,6 +52,24 @@ jobs:
node-version: 20
check-latest: true
- name: Create GitHub App token
id: release-app-token
uses: actions/create-github-app-token@v3
with:
client-id: ${{ vars.RELEASE_GITHUB_APP_CLIENT_ID }}
private-key: ${{ secrets.RELEASE_GITHUB_APP_PRIVATE_KEY }}
owner: ${{ github.repository_owner }}
repositories: next.js
permission-contents: write
- name: Get GitHub App user ID
id: release-app-user
run: |
user_id="$(gh api "/users/${{ steps.release-app-token.outputs.app-slug }}[bot]" --jq .id)"
echo "user-id=$user_id" >> "$GITHUB_OUTPUT"
env:
GH_TOKEN: ${{ steps.release-app-token.outputs.token }}
- name: Clone Next.js repository
run: git clone https://github.com/vercel/next.js.git --depth=25 --single-branch --branch ${GITHUB_REF_NAME:-canary} .
......@@ -61,10 +79,13 @@ jobs:
# Ignoring failures for now to check if a failure truly implies a failed publish.
continue-on-error: true
env:
GITHUB_TOKEN: ${{ secrets.RELEASE_BOT_GITHUB_TOKEN }}
GH_TOKEN: ${{ steps.release-app-token.outputs.token }}
- name: Get commit of the latest tag
run: echo "LATEST_TAG_COMMIT=$(git rev-list -n 1 $(git describe --tags --abbrev=0))" >> $GITHUB_ENV
run: |
git fetch --tags --force --deepen=1000 origin
latest_tag="$(git describe --tags --abbrev=0)"
echo "LATEST_TAG_COMMIT=$(git rev-list -n 1 "$latest_tag")" >> $GITHUB_ENV
- name: Get latest commit
run: echo "LATEST_COMMIT=$(git rev-parse HEAD)" >> $GITHUB_ENV
......@@ -102,6 +123,8 @@ jobs:
- run: node ./scripts/start-release.js --release-type "${INPUT_RELEASETYPE}" --semver-type "${INPUT_SEMVERTYPE}"
env:
RELEASE_BOT_GITHUB_TOKEN: ${{ secrets.RELEASE_BOT_GITHUB_TOKEN }}
RELEASE_GITHUB_TOKEN: ${{ steps.release-app-token.outputs.token }}
RELEASE_GITHUB_APP_SLUG: ${{ steps.release-app-token.outputs.app-slug }}
RELEASE_GITHUB_APP_USER_ID: ${{ steps.release-app-user.outputs.user-id }}
INPUT_RELEASETYPE: ${{ github.event.inputs.releaseType || 'canary' }}
INPUT_SEMVERTYPE: ${{ github.event.inputs.semverType }}
......@@ -20,8 +20,11 @@ concurrency:
env:
CI: 1
RUST_LOG: 'off'
TURBO_TEAM: 'vercel'
TURBO_CACHE: 'remote:rw'
TURBO_TEAM: 'vtest314-next-adapter-e2e-tests'
# Prefer shared remote cache across runs, but keep local cache enabled so jobs
# degrade gracefully if the remote cache or token is unavailable.
TURBO_CACHE: 'local:rw,remote:rw'
TURBO_TOKEN: ${{ secrets.TURBO_TOKEN }}
permissions:
contents: read
......@@ -30,7 +33,7 @@ permissions:
jobs:
benchmark-small-apps:
name: Benchmark Rust Crates (small apps)
runs-on: ['self-hosted', 'linux', 'x64', 'metal']
runs-on: ubuntu-latest-16-core-oss
steps:
- uses: actions/checkout@v4
......@@ -43,7 +46,7 @@ jobs:
- name: Start sccache
uses: ./.github/actions/sccache
with:
turbo-token: ${{ secrets.TURBO_REMOTE_CACHE_TOKEN }}
turbo-token: ${{ secrets.TURBO_TOKEN }}
- name: Install pnpm dependencies
working-directory: turbopack/benchmark-apps
......@@ -65,7 +68,7 @@ jobs:
benchmark-analyzer:
name: Benchmark Rust Crates (analyzer)
runs-on: ['self-hosted', 'linux', 'x64', 'metal']
runs-on: ubuntu-latest-16-core-oss
steps:
- uses: actions/checkout@v4
......@@ -78,7 +81,7 @@ jobs:
- name: Start sccache
uses: ./.github/actions/sccache
with:
turbo-token: ${{ secrets.TURBO_REMOTE_CACHE_TOKEN }}
turbo-token: ${{ secrets.TURBO_TOKEN }}
- name: Install pnpm dependencies
working-directory: turbopack/benchmark-apps
......@@ -101,7 +104,7 @@ jobs:
benchmark-large:
name: Benchmark Rust Crates (large)
if: ${{ github.event.label.name == 'benchmark' || github.event_name == 'workflow_dispatch' }}
runs-on: ['self-hosted', 'linux', 'x64', 'metal']
runs-on: ubuntu-latest-16-core-oss
steps:
- uses: actions/checkout@v4
......@@ -114,7 +117,7 @@ jobs:
- name: Start sccache
uses: ./.github/actions/sccache
with:
turbo-token: ${{ secrets.TURBO_REMOTE_CACHE_TOKEN }}
turbo-token: ${{ secrets.TURBO_TOKEN }}
- name: Build the benchmark target(s)
env:
......
name: Poll React Sync
on:
schedule:
# GitHub runs cronjobs at most every 5 minutes.
# Ideally we get 2 minutes or lower which is what we used to have with Vercel cronjobs.
- cron: '*/5 * * * *'
concurrency:
group: poll-react-sync
cancel-in-progress: true
jobs:
poll:
runs-on: ubuntu-latest
permissions:
actions: write
steps:
# We're using react@experimental as a signal for a new React sync because
# in facebook/react we publish experimental after canary. If we would just
# look at canary, we might update before experimental is published.
- name: Fetch latest react@experimental version
id: current
run: |
CURRENT=$(npm --silent view --json react@experimental version | tr -d '"')
if [ -z "$CURRENT" ]; then
echo "Failed to resolve react@experimental version" >&2
exit 1
fi
echo "version=$CURRENT" >> "$GITHUB_OUTPUT"
echo "Current react@experimental: $CURRENT"
- name: Check whether this version was already seen
id: cache
uses: actions/cache@v4
with:
# The key encodes the version. Cache hit = already processed; cache miss = new version.
# The path just needs to exist so the post-step can save the cache entry on a miss.
path: .cache/marker
key: react-experimental-${{ steps.current.outputs.version }}
- name: Mark version as seen
if: steps.cache.outputs.cache-hit != 'true'
run: |
mkdir -p .cache
printf '%s' '${{ steps.current.outputs.version }}' > .cache/marker
- name: Resolve corresponding react@canary version
id: canary
if: steps.cache.outputs.cache-hit != 'true'
run: |
CANARY=$(npm --silent view --json react@canary version | tr -d '"')
if [ -z "$CANARY" ]; then
echo "Failed to resolve react@canary version" >&2
exit 1
fi
echo "version=$CANARY" >> "$GITHUB_OUTPUT"
echo "Current react@canary: $CANARY"
- name: Dispatch update_react.yml
if: steps.cache.outputs.cache-hit != 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
EXPERIMENTAL: ${{ steps.current.outputs.version }}
CANARY: ${{ steps.canary.outputs.version }}
run: |
echo "react@experimental changed to $EXPERIMENTAL. Dispatching update_react.yml with react@canary=$CANARY."
gh workflow run update_react.yml --ref ${{ github.ref_name }} -f version="$CANARY"
# This workflow uploads preview tarballs to Vercel Blob after build-and-deploy
# completes. It uses workflow_run so it always executes the DEFAULT BRANCH
# version of this file -- an attacker who modifies this file on a feature branch
# cannot change the code that touches the blob write token.
name: upload-preview-tarballs
on:
workflow_run:
workflows: ['build-and-deploy']
types: [completed]
env:
NODE_LTS_VERSION: 20
permissions:
actions: read
contents: read
jobs:
upload:
name: Upload preview tarballs to Blob
runs-on: ubuntu-latest
if: github.event.workflow_run.conclusion == 'success'
environment: preview-builds
steps:
- name: Setup node
uses: actions/setup-node@v6
with:
node-version: ${{ env.NODE_LTS_VERSION }}
check-latest: true
# Checkout from the default branch (canary) -- workflow_run always uses
# the default branch's version of the workflow file and this checkout
# matches that, ensuring the upload script is trusted.
- uses: actions/checkout@v6
with:
ref: ${{ github.event.repository.default_branch }}
fetch-depth: 1
- name: Enable corepack
run: corepack enable
- name: Setup pnpm
run: corepack prepare
- name: Cache dependencies
uses: actions/cache@v3
with:
path: ~/.pnpm-store
key: ${{ runner.os }}-${{ runner.arch }}-pnpm-v2-${{
hashFiles('**/pnpm-lock.yaml') }}
# Do not use restore-keys since it leads to indefinite growth of the cache.
- name: Install node_modules
run: pnpm install --frozen-lockfile
- name: Download preview-tarballs artifact
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
with:
name: preview-tarballs
path: ${{ runner.temp }}/preview-tarballs
github-token: ${{ secrets.GITHUB_TOKEN }}
run-id: ${{ github.event.workflow_run.id }}
- name: Upload tarballs to Vercel Blob
run: node scripts/upload-preview-tarballs.js "${{
github.event.workflow_run.head_sha }}" "${{ runner.temp
}}/preview-tarballs"
env:
BLOB_READ_WRITE_TOKEN: ${{ secrets.PREVIEW_BUILDS_BLOB_READ_WRITE_TOKEN }}
This diff is collapsed.
......@@ -249,14 +249,14 @@ async-trait = "0.1.64"
bincode = { version = "2.0.1", features = ["serde"] }
bitfield = "0.19.4"
byteorder = "1.5.0"
bytes = "1.1.0"
bytes = "1.11.1"
bytes-str = "0.2.7"
chrono = "0.4.23"
clap = { version = "4.5.2", features = ["derive"] }
concurrent-queue = "2.5.0"
console-subscriber = "0.4.1"
const_format = "0.2.30"
crc32fast = "1.4.2"
crc32fast = "1.5.0"
criterion = { package = "codspeed-criterion-compat", version = "4.3.0" }
ctor = "0.8"
crossbeam-channel = "0.5.8"
......@@ -288,7 +288,7 @@ lightningcss-napi = { version = "0.4.6", default-features = false, features = [
] }
lzzzz = "2.0.0"
markdown = "1.0.0-alpha.18"
memchr = "2.7.4"
memchr = "2.8.0"
mime = "0.3.16"
napi = { version = "2", default-features = false, features = [
"napi3",
......@@ -311,27 +311,27 @@ parking_lot = "0.12.1"
pathdiff = "0.2.1"
phf = { version = "0.11", features = ["macros"] }
petgraph = "0.8.3"
pin-project-lite = "0.2.9"
pin-project-lite = "0.2.17"
postcard = "1.0.4"
proc-macro2 = "1.0.79"
qstring = "0.7.2"
quick_cache = { version = "0.6.14" }
quote = "1.0.23"
rand = "0.10.0"
quote = "1.0.45"
rand = "0.10.1"
rayon = "1.10.0"
regex = "1.10.6"
regex = "1.12.3"
regress = "0.10.4"
reqwest = { version = "0.13.2", default-features = false }
ringmap = "0.2.3"
roaring = "0.10.10"
ringmap = "0.2.5"
roaring = "0.11.4"
rstest = "0.16.0"
rustc-hash = "2.1.1"
semver = "1.0.16"
serde = { version = "1.0.217", features = ["derive"] }
serde_json = "1.0.138"
serde_path_to_error = "0.1.16"
serde_qs = "0.13.0"
serde_with = "3.12.0"
serde = { version = "1.0.228", features = ["derive"] }
serde_json = "1.0.149"
serde_path_to_error = "0.1.20"
serde_qs = "1.1.1"
serde_with = "3.18.0"
sha2 = "0.10.2"
smallvec = { version = "1.15.1", features = [
"serde",
......@@ -350,7 +350,7 @@ thiserror = "1.0.48"
thread_local = "1.1.8"
tokio = "~1.47.3"
tokio-util = { version = "0.7.13", features = ["io", "rt"] }
tracing = "0.1.37"
tracing = "0.1.44"
tracing-subscriber = "0.3.16"
triomphe = { git = "https://github.com/sokra/triomphe", branch = "sokra/unstable" }
xxhash-rust = { version = "0.8.12", features = ["xxh3"] }
......
......@@ -35,11 +35,10 @@
"@types/react": "^18",
"@types/react-dom": "^18",
"cross-env": "10.1.0",
"eslint": "catalog:",
"inliner": "1.13.1",
"postcss": "^8.5",
"tailwindcss": "^4.1.9",
"tw-animate-css": "1.3.3",
"typescript": "catalog:"
"typescript": "6.0.2"
}
}
......@@ -5,6 +5,16 @@
- Read about our [Commitment to Open Source](https://vercel.com/oss).
- Before jumping into a PR be sure to search [existing PRs](https://github.com/vercel/next.js/pulls) or [issues](https://github.com/vercel/next.js/issues) for an open or closed item that relates to your submission.
## Signed commits
This repository requires verified commit signatures on protected branches.
Before contributing, configure Git to sign your commits with a GitHub-verified GPG, SSH, or S/MIME key. Unsigned commits will be rejected by the repository rules and will need to be rewritten as signed commits before they can be merged.
If a pull request includes unsigned commits, re-sign the commits and force-push the branch. Make sure the signing key is added to your GitHub account and that your commits appear as `Verified`.
A `Signed-off-by` line in the commit message is not enough to satisfy this requirement.
## Repository
- [Triaging](./contributing/repository/triaging.md)
......
......@@ -966,7 +966,7 @@ impl AppProject {
graphs.push(graph);
visited_modules = VisitedModules::concatenate(visited_modules, graph);
let base = ModuleGraph::from_graphs(graphs.clone());
let base = ModuleGraph::from_graphs(graphs.clone(), None);
let additional_entries = endpoint.additional_entries(base.connect());
let additional_module_graph = SingleModuleGraph::new_with_entries_visited_intern(
additional_entries.owned().await?,
......@@ -991,20 +991,18 @@ impl AppProject {
.await?;
let (full, binding_usage_info) = if remove_unused_imports {
let full_with_unused_references = ModuleGraph::from_graphs(graphs.clone());
let full_with_unused_references =
ModuleGraph::from_graphs(graphs.clone(), None);
let binding_usage_info = compute_binding_usage_info(
full_with_unused_references,
should_read_binding_usage,
);
(
ModuleGraph::from_graphs_without_unused_references(
graphs,
binding_usage_info,
),
ModuleGraph::from_graphs(graphs, Some(binding_usage_info)),
Some(binding_usage_info),
)
} else {
(ModuleGraph::from_graphs(graphs), None)
(ModuleGraph::from_graphs(graphs, None), None)
};
Ok(BaseAndFullModuleGraph {
......
......@@ -31,9 +31,9 @@ pub struct ClientReferenceData(FxHashMap<ResolvedVc<Box<dyn Module>>, ClientMani
pub async fn map_client_references(
graph: ResolvedVc<ModuleGraphLayer>,
) -> Result<Vc<ClientReferenceData>> {
let graph = graph.await?;
let manifest = graph
.iter_nodes()
.await?
.iter_reachable_modules()?
.map(|module| async move {
if let Some(client_reference_module) =
ResolvedVc::try_downcast_type::<EcmascriptClientReferenceModule>(module)
......
......@@ -120,38 +120,36 @@ pub struct DynamicImportEntries(
pub async fn map_next_dynamic(
graph: ResolvedVc<ModuleGraphLayer>,
) -> Result<Vc<DynamicImportEntries>> {
let actions = graph
.await?
.iter_nodes()
.map(|module| async move {
if module
.ident()
.await?
.layer
.as_ref()
.is_some_and(|layer| layer.name() == "app-client" || layer.name() == "client")
&& let Some(dynamic_entry_module) =
let actions =
graph
.await?
.iter_reachable_modules()?
.map(|module| async move {
if let Some(dynamic_entry_module) =
ResolvedVc::try_downcast_type::<NextDynamicEntryModule>(module)
{
return Ok(Some((
module,
DynamicImportEntriesMapType::DynamicEntry(dynamic_entry_module),
)));
}
// TODO add this check once these modules have the correct layer
// if layer.is_some_and(|layer| &**layer == "app-rsc") {
if let Some(client_reference_module) =
ResolvedVc::try_downcast_type::<EcmascriptClientReferenceModule>(module)
{
return Ok(Some((
module,
DynamicImportEntriesMapType::ClientReference(client_reference_module),
)));
}
// }
Ok(None)
})
.try_flat_join()
.await?;
&& module.ident().await?.layer.as_ref().is_some_and(|layer| {
layer.name() == "app-client" || layer.name() == "client"
})
{
return Ok(Some((
module,
DynamicImportEntriesMapType::DynamicEntry(dynamic_entry_module),
)));
}
// TODO add this check once these modules have the correct layer
// if layer.is_some_and(|layer| &**layer == "app-rsc") {
if let Some(client_reference_module) =
ResolvedVc::try_downcast_type::<EcmascriptClientReferenceModule>(module)
{
return Ok(Some((
module,
DynamicImportEntriesMapType::ClientReference(client_reference_module),
)));
}
// }
Ok(None)
})
.try_flat_join()
.await?;
Ok(Vc::cell(actions.into_iter().collect()))
}
......@@ -753,11 +753,11 @@ impl PageEndpoint {
.await?;
let graph = if remove_unused_imports {
let graph = ModuleGraph::from_graphs(graphs.clone());
let graph = ModuleGraph::from_graphs(graphs.clone(), None);
let binding_usage_info = compute_binding_usage_info(graph, true);
ModuleGraph::from_graphs_without_unused_references(graphs, binding_usage_info)
ModuleGraph::from_graphs(graphs, Some(binding_usage_info))
} else {
ModuleGraph::from_graphs(graphs)
ModuleGraph::from_graphs(graphs, None)
};
Ok(graph.connect())
......
......@@ -1452,11 +1452,14 @@ impl Project {
) -> Result<Vc<ModuleGraph>> {
Ok(if *self.per_page_module_graph().await? {
let is_production = self.next_mode().await?.is_production();
ModuleGraph::from_single_graph(SingleModuleGraph::new_with_entry(
ChunkGroupEntry::Entry(vec![entry]),
is_production,
is_production,
))
ModuleGraph::from_graphs(
vec![SingleModuleGraph::new_with_entry(
ChunkGroupEntry::Entry(vec![entry]),
is_production,
is_production,
)],
None,
)
.connect()
} else {
*self.whole_app_module_graphs().await?.full
......@@ -1476,11 +1479,14 @@ impl Project {
.copied()
.map(ResolvedVc::upcast)
.collect();
ModuleGraph::from_single_graph(SingleModuleGraph::new_with_entries(
ResolvedVc::cell(vec![ChunkGroupEntry::Entry(entries)]),
is_production,
is_production,
))
ModuleGraph::from_graphs(
vec![SingleModuleGraph::new_with_entries(
ResolvedVc::cell(vec![ChunkGroupEntry::Entry(entries)]),
is_production,
is_production,
)],
None,
)
.connect()
} else {
*self.whole_app_module_graphs().await?.full
......@@ -2485,7 +2491,7 @@ async fn whole_app_module_graph_operation(
);
let base_visited_modules = VisitedModules::from_graph(base_single_module_graph);
let base = ModuleGraph::from_single_graph(base_single_module_graph);
let base = ModuleGraph::from_graphs(vec![base_single_module_graph], None);
let turbopack_remove_unused_imports = *project
.next_config()
......@@ -2496,10 +2502,7 @@ async fn whole_app_module_graph_operation(
// TODO suboptimal that we do compute_binding_usage_info twice (once for the base
// graph and later for the full graph)
let binding_usage_info = compute_binding_usage_info(base, true);
ModuleGraph::from_single_graph_without_unused_references(
base_single_module_graph,
binding_usage_info,
)
ModuleGraph::from_graphs(vec![base_single_module_graph], Some(binding_usage_info))
} else {
base
};
......@@ -2535,14 +2538,14 @@ async fn whole_app_module_graph_operation(
let graphs = vec![base_single_module_graph, additional_module_graph];
let (full, binding_usage_info) = if turbopack_remove_unused_imports {
let full_with_unused_references = ModuleGraph::from_graphs(graphs.clone());
let full_with_unused_references = ModuleGraph::from_graphs(graphs.clone(), None);
let binding_usage_info = compute_binding_usage_info(full_with_unused_references, true);
(
ModuleGraph::from_graphs_without_unused_references(graphs, binding_usage_info),
ModuleGraph::from_graphs(graphs, Some(binding_usage_info)),
Some(binding_usage_info),
)
} else {
(ModuleGraph::from_graphs(graphs), None)
(ModuleGraph::from_graphs(graphs, None), None)
};
Ok(BaseAndFullModuleGraph {
......
......@@ -527,7 +527,7 @@ pub async fn map_server_actions(
) -> Result<Vc<AllModuleActions>> {
let actions = graph
.await?
.iter_nodes()
.iter_reachable_modules()?
.map(async |module| {
// TODO: compare module contexts instead?
let layer = match module.ident().await?.layer.as_ref() {
......
......@@ -20,7 +20,7 @@ swc_core = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["full"] }
tokio-stream = "0.1.15"
tracing = "0.1"
tracing = { workspace = true }
tracing-subscriber = "0.3"
turbo-rcstr = { workspace = true }
turbo-tasks = { workspace = true }
......
......@@ -254,7 +254,7 @@ async fn endpoint_write_to_disk_with_apply(
endpoint_write_to_disk(*endpoint)
}
#[turbo_tasks::value(serialization = "none")]
#[turbo_tasks::value(serialization = "skip")]
struct WithEffects {
output_paths: ReadRef<EndpointOutputPaths>,
effects: Effects,
......
......@@ -32,12 +32,6 @@ pub async fn get_next_client_transforms_rules(
let modularize_imports_config = next_config.modularize_imports();
let enable_mdx_rs = next_config.mdx_rs().await?.is_some();
let page_extensions: Vec<String> = next_config
.page_extensions()
.await?
.iter()
.map(|s| s.to_string())
.collect();
if !foreign_code {
rules.push(get_next_lint_transform_rule(enable_mdx_rs).await?);
......@@ -83,7 +77,7 @@ pub async fn get_next_client_transforms_rules(
ExportFilter::StripDataExports,
enable_mdx_rs,
vec![],
&page_extensions,
&next_config.page_extensions().await?,
)
.await?,
);
......
......@@ -774,11 +774,14 @@ async fn get_mock_stylesheet(
.module();
let entries = get_evaluate_entries(mocked_response_asset, asset_context, *node_backend, None);
let module_graph = ModuleGraph::from_single_graph(SingleModuleGraph::new_with_entries(
entries.graph_entries().to_resolved().await?,
false,
false,
));
let module_graph = ModuleGraph::from_graphs(
vec![SingleModuleGraph::new_with_entries(
entries.graph_entries().to_resolved().await?,
false,
false,
)],
None,
);
let module_graph = module_graph.connect();
let root = mock_fs.root().owned().await?;
......
......@@ -38,13 +38,7 @@ pub async fn get_next_server_transforms_rules(
let mut rules = vec![];
let modularize_imports_config = next_config.modularize_imports();
let mdx_rs = next_config.mdx_rs().await?.is_some();
let page_extensions: Vec<String> = next_config
.page_extensions()
.await?
.iter()
.map(|s| s.to_string())
.collect();
let mdx_rs: bool = next_config.mdx_rs().await?.is_some();
if !foreign_code {
rules.push(get_next_lint_transform_rule(mdx_rs).await?);
......@@ -92,7 +86,7 @@ pub async fn get_next_server_transforms_rules(
vec![RuleCondition::ReferenceType(ReferenceTypeCondition::Entry(
Some(EntryReferenceSubType::PageData),
))],
&page_extensions,
&next_config.page_extensions().await?,
)
.await?,
);
......@@ -157,7 +151,7 @@ pub async fn get_next_server_transforms_rules(
};
if is_app_dir {
rules.push(get_next_debug_instant_stack_rule(mdx_rs, page_extensions.clone()).await?);
rules.push(get_next_debug_instant_stack_rule(mdx_rs, next_config.page_extensions()).await?);
}
if is_app_dir &&
......
use anyhow::Result;
use async_trait::async_trait;
use next_custom_transforms::transforms::debug_instant_stack::debug_instant_stack;
use next_custom_transforms::transforms::debug_instant_stack::DebugInstantStack;
use swc_core::ecma::ast::Program;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, Vc};
use turbopack::module_options::{ModuleRule, ModuleRuleEffect};
use turbopack_ecmascript::{
......@@ -12,9 +13,9 @@ use super::module_rule_match_js_no_url;
pub async fn get_next_debug_instant_stack_rule(
enable_mdx_rs: bool,
page_extensions: Vec<String>,
page_extensions: Vc<Vec<RcStr>>,
) -> Result<ModuleRule> {
let transform = EcmascriptInputTransform::Plugin(
let transform: EcmascriptInputTransform = EcmascriptInputTransform::Plugin(
next_debug_instant_stack_transform_plugin(page_extensions)
.to_resolved()
.await?,
......@@ -32,24 +33,27 @@ pub async fn get_next_debug_instant_stack_rule(
}
#[turbo_tasks::function]
fn next_debug_instant_stack_transform_plugin(page_extensions: Vec<String>) -> Vc<TransformPlugin> {
Vc::cell(Box::new(NextDebugInstantStack { page_extensions })
as Box<dyn CustomTransformer + Send + Sync>)
async fn next_debug_instant_stack_transform_plugin(
page_extensions: ResolvedVc<Vec<RcStr>>,
) -> Result<Vc<TransformPlugin>> {
Ok(Vc::cell(Box::new(NextDebugInstantStack {
debug_instant_stack: DebugInstantStack::new(&*page_extensions.await?),
}) as Box<dyn CustomTransformer + Send + Sync>))
}
#[derive(Debug)]
struct NextDebugInstantStack {
page_extensions: Vec<String>,
debug_instant_stack: DebugInstantStack,
}
#[async_trait]
impl CustomTransformer for NextDebugInstantStack {
#[tracing::instrument(level = tracing::Level::TRACE, name = "debug_instant_stack", skip_all)]
async fn transform(&self, program: &mut Program, ctx: &TransformContext<'_>) -> Result<()> {
program.mutate(debug_instant_stack(
ctx.file_path_str.to_string(),
self.page_extensions.clone(),
));
program.mutate(
self.debug_instant_stack
.get_pass(ctx.file_path_str.to_string()),
);
Ok(())
}
}
......@@ -5,6 +5,7 @@ use next_custom_transforms::transforms::strip_page_exports::{
ExportFilter, next_transform_strip_page_exports,
};
use swc_core::ecma::ast::Program;
use turbo_rcstr::RcStr;
use turbo_tasks::{ResolvedVc, TaskInput, Vc, trace::TraceRawVcs};
use turbo_tasks_fs::FileSystemPath;
use turbopack::module_options::{ModuleRule, ModuleRuleEffect, RuleCondition};
......@@ -45,7 +46,7 @@ pub async fn get_next_pages_transforms_rule(
export_filter: ExportFilter,
enable_mdx_rs: bool,
extra_conditions: Vec<RuleCondition>,
page_extensions: &[String],
page_extensions: &[RcStr],
) -> Result<ModuleRule> {
// Apply the Next SSG transform to all pages.
let strip_transform = EcmascriptInputTransform::Plugin(
......
......@@ -23,7 +23,7 @@ rustc-hash = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true, features = ["preserve_order"] }
sha1 = "0.10.1"
tracing = { version = "0.1.37" }
tracing = { workspace = true }
anyhow = { workspace = true }
swc_core = { workspace = true, features = [
......
......@@ -348,15 +348,15 @@ where
crate::transforms::debug_fn_name::debug_fn_name(),
opts.debug_function_name,
),
crate::transforms::debug_instant_stack::debug_instant_stack(
file_path_for_instant_stack,
crate::transforms::debug_instant_stack::DebugInstantStack::new(
match &opts.server_components {
Some(react_server_components::Config::WithOptions(options)) => {
options.page_extensions.clone()
}
_ => vec![],
},
),
)
.get_pass(file_path_for_instant_stack),
visit_mut_pass(crate::transforms::pure::pure_magic(comments.clone())),
Optional::new(
linter(lint_codemod_comments(comments)),
......
......@@ -8,30 +8,48 @@ use swc_core::{
quote,
};
fn build_page_extensions_regex(page_extensions: &[String]) -> String {
if page_extensions.is_empty() {
"(ts|js)x?".to_string()
} else {
let escaped: Vec<String> = page_extensions
.iter()
.map(|ext| regex::escape(ext))
.collect();
format!("({})", escaped.join("|"))
}
#[derive(Debug)]
pub struct DebugInstantStack {
page_or_layout: Regex,
}
pub fn debug_instant_stack(filepath: String, page_extensions: Vec<String>) -> impl Pass {
visit_mut_pass(DebugInstantStack {
filepath,
instant_export_span: None,
page_extensions,
})
impl DebugInstantStack {
pub fn new<I, S>(page_extensions: I) -> Self
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
let mut result = String::from(r"[\\/](page|layout|default)\.");
let mut iter = page_extensions.into_iter();
if let Some(first) = iter.next() {
result.push('(');
result.push_str(&regex::escape(first.as_ref()));
for ext in iter {
result.push('|');
result.push_str(&regex::escape(ext.as_ref()));
}
result.push(')');
} else {
result.push_str("(ts|js)x?");
}
result.push('$');
Self {
page_or_layout: Regex::new(&result).unwrap(),
}
}
pub fn get_pass(&self, filepath: String) -> impl Pass + use<> {
visit_mut_pass(DebugInstantStackPass {
filepath,
instant_export_span: None,
page_or_layout: self.page_or_layout.clone(),
})
}
}
struct DebugInstantStack {
struct DebugInstantStackPass {
filepath: String,
instant_export_span: Option<Span>,
page_extensions: Vec<String>,
page_or_layout: Regex,
}
/// Given an export specifier, returns `Some((exported_name, local_name))` if
......@@ -80,12 +98,9 @@ fn find_var_init_span(items: &[ModuleItem], local_name: &str) -> Option<Span> {
None
}
impl VisitMut for DebugInstantStack {
impl VisitMut for DebugInstantStackPass {
fn visit_mut_module_items(&mut self, items: &mut Vec<ModuleItem>) {
let ext_pattern = build_page_extensions_regex(&self.page_extensions);
let page_or_layout_re =
Regex::new(&format!(r"[\\/](page|layout|default)\.{ext_pattern}$")).unwrap();
if !page_or_layout_re.is_match(&self.filepath) {
if !self.page_or_layout.is_match(&self.filepath) {
return;
}
......
......@@ -8,7 +8,7 @@ use bytes_str::BytesStr;
use next_custom_transforms::transforms::{
cjs_optimizer::cjs_optimizer,
debug_fn_name::debug_fn_name,
debug_instant_stack::debug_instant_stack,
debug_instant_stack::DebugInstantStack,
dynamic::{NextDynamicMode, next_dynamic},
fonts::{Config as FontLoaderConfig, next_font_loaders},
named_import_transform::named_import_transform,
......@@ -878,7 +878,7 @@ fn test_debug_instant_stack(input: PathBuf) {
test_fixture(
syntax(),
&|_| debug_instant_stack("app/page.js".to_string(), vec![]),
&|_| DebugInstantStack::new::<Vec<&str>, &str>(vec![]).get_pass("app/page.js".to_string()),
&input,
&output,
FixtureTestConfig {
......
......@@ -4,7 +4,9 @@ use serde_json::Value;
fn main() -> anyhow::Result<()> {
println!("cargo:rerun-if-env-changed=CI");
println!("cargo:rerun-if-env-changed=CARGO_CFG_TARGET_OS");
let is_ci = env::var("CI").is_ok_and(|value| !value.is_empty());
let is_macos_target = env::var("CARGO_CFG_TARGET_OS").is_ok_and(|value| value == "macos");
let nextjs_version = {
let package_json_path = Path::new(env!("CARGO_MANIFEST_DIR"))
......@@ -68,12 +70,12 @@ fn main() -> anyhow::Result<()> {
_ => println!("cargo:warning=`git rev-parse HEAD` failed"),
}
#[cfg(not(all(target_os = "macos", target_arch = "aarch64")))]
napi_build::setup();
if !is_macos_target {
napi_build::setup();
}
// This is a workaround for napi always including a GCC specific flag.
#[cfg(all(target_os = "macos", target_arch = "aarch64"))]
{
// This is a workaround for napi always including a GCC-specific flag on macOS.
if is_macos_target {
println!("cargo:rerun-if-env-changed=DEBUG_GENERATED_CODE");
println!("cargo:rerun-if-env-changed=TYPE_DEF_TMP_PATH");
println!("cargo:rerun-if-env-changed=CARGO_CFG_NAPI_RS_CLI_VERSION");
......
......@@ -15,7 +15,7 @@ use turbopack_core::{
use crate::next_api::utils::strongly_consistent_catch_collectables;
#[turbo_tasks::value(serialization = "none")]
#[turbo_tasks::value(serialization = "skip")]
pub struct WriteAnalyzeResult {
pub issues: Arc<Vec<ReadRef<PlainIssue>>>,
pub diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
......
......@@ -115,7 +115,7 @@ async fn issue_filter_from_endpoint(
}
}
#[turbo_tasks::value(serialization = "none")]
#[turbo_tasks::value(serialization = "skip")]
struct WrittenEndpointWithIssues {
written: Option<ReadRef<EndpointOutputPaths>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
......@@ -215,7 +215,7 @@ pub fn endpoint_server_changed_subscribe(
)
}
#[turbo_tasks::value(shared, serialization = "none", eq = "manual")]
#[turbo_tasks::value(shared, serialization = "skip", eq = "manual")]
struct EndpointIssuesAndDiags {
changed: Option<ReadRef<Completion>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
......
......@@ -454,10 +454,28 @@ pub fn project_new(
}
let mut compress = Compression::None;
if let Some(mut trace) = trace {
let internal_dir = PathBuf::from(&options.root_path)
.join(&options.project_path)
.join(".next-profiles");
let trace_file = internal_dir.join("trace-turbopack");
let trace_path_override = std::env::var_os("NEXT_TURBOPACK_TRACING_PATH")
.filter(|v| !v.is_empty())
.map(PathBuf::from);
let trace_file = if let Some(path) = trace_path_override {
if path.is_absolute() {
path
} else {
std::env::current_dir()
.context("Unable to read current working directory")
.unwrap()
.join(path)
}
} else {
PathBuf::from(&options.root_path)
.join(&options.project_path)
.join(".next-profiles")
.join("trace-turbopack")
};
let trace_dir = trace_file
.parent()
.expect("Trace file path must have a parent directory")
.to_path_buf();
println!("Turbopack tracing enabled with targets: {trace}");
println!(" Note that this might have a small performance impact.");
......@@ -496,8 +514,13 @@ pub fn project_new(
let subscriber = subscriber.with(FilterLayer::try_new(&trace).unwrap());
std::fs::create_dir_all(&internal_dir)
.context("Unable to create .next-profiles directory")
std::fs::create_dir_all(&trace_dir)
.with_context(|| {
format!(
"Unable to create trace output directory {}",
trace_dir.display()
)
})
.unwrap();
let (trace_writer, trace_writer_guard) = match compress {
Compression::None => {
......@@ -965,7 +988,7 @@ impl NapiEntrypoints {
}
}
#[turbo_tasks::value(serialization = "none")]
#[turbo_tasks::value(serialization = "skip")]
struct EntrypointsWithIssues {
entrypoints: Option<ReadRef<EntrypointsOperation>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
......@@ -1000,14 +1023,14 @@ fn project_container_entrypoints_operation(
container.entrypoints()
}
#[turbo_tasks::value(serialization = "none")]
#[turbo_tasks::value(serialization = "skip")]
struct OperationResult {
issues: Arc<Vec<ReadRef<PlainIssue>>>,
diagnostics: Arc<Vec<ReadRef<PlainDiagnostic>>>,
effects: Arc<Effects>,
}
#[turbo_tasks::value(serialization = "none")]
#[turbo_tasks::value(serialization = "skip")]
struct AllWrittenEntrypointsWithIssues {
entrypoints: Option<ReadRef<EntrypointsOperation>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
......@@ -1800,7 +1823,7 @@ pub fn project_entrypoints_subscribe(
)
}
#[turbo_tasks::value(serialization = "none")]
#[turbo_tasks::value(serialization = "skip")]
struct HmrUpdateWithIssues {
update: ReadRef<Update>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
......@@ -1945,7 +1968,7 @@ struct HmrChunkNames {
pub chunk_names: Vec<RcStr>,
}
#[turbo_tasks::value(serialization = "none")]
#[turbo_tasks::value(serialization = "skip")]
struct HmrChunkNamesWithIssues {
chunk_names: ReadRef<Vec<RcStr>>,
issues: Arc<Vec<ReadRef<PlainIssue>>>,
......
......@@ -125,7 +125,7 @@ Generating source maps consumes extra memory during the build process.
You can disable source map generation by adding `productionBrowserSourceMaps: false` and `experimental.serverSourceMaps: false` to your Next.js configuration.
When using the `cacheComponents` feature, Next.js will use source maps by default during the prerender phase of `next build`.
Next.js will use source maps by default during the prerender phase of `next build`.
If you consistently encounter memory issues during that phase (after "Generating static pages"),
you can try disabling source maps in that phase by adding `enablePrerenderSourceMaps: false` to your Next.js configuration.
......
......@@ -533,6 +533,18 @@ aren’t supported by Next.js. You need to update their usage as follows:
- `import.meta.env.DEV` ⇒ `process.env.NODE_ENV !== 'production'`
- `import.meta.env.SSR` ⇒ `typeof window !== 'undefined'`
**`import.meta.glob`** is supported by Turbopack (the default Next.js bundler) with no changes needed. If you were using the `as` option (deprecated in Vite 5), replace it with `query`:
```js
// Before (Vite)
const modules = import.meta.glob('./dir/*.txt', { as: 'raw' })
// After (Next.js / Turbopack)
const modules = import.meta.glob('./dir/*.txt', { query: '?raw' })
```
See the [import.meta.glob docs](/docs/app/api-reference/turbopack#importmetaglob) for the full API.
Next.js also doesn't provide a built-in `BASE_URL` environment variable. However, you can still
configure one, if you need it:
......
......@@ -288,8 +288,6 @@ This enables several experimental options to make debugging easier:
- `experimental.turbopackMinify = false`
- Generates source maps for server bundles:
- `experimental.serverSourceMaps = true`
- Enables source map consumption in child processes used for prerendering:
- `enablePrerenderSourceMaps = true`
- Continues building even after the first prerender error, so you can see all issues at once:
- `experimental.prerenderEarlyExit = false`
......
......@@ -137,6 +137,112 @@ Turbopack supports webpack-compatible magic comments for controlling import beha
See [Lazy Loading](/docs/app/guides/lazy-loading#magic-comments) for usage examples.
## import.meta.glob
Turbopack supports `import.meta.glob()`, a Vite-compatible API for importing multiple modules at once using glob patterns. The result is an object keyed by the file path relative to the calling file.
```js
const modules = import.meta.glob('./dir/*.js')
// {
// './dir/foo.js': () => import('./dir/foo.js'),
// './dir/bar.js': () => import('./dir/bar.js'),
// }
```
> **Good to know:** `import.meta.glob` requires Turbopack. It is not available when using webpack.
### Lazy loading (default)
By default, each value in the result object is a thunk — a function that returns a `Promise` for the module. This enables lazy loading:
```js
const modules = import.meta.glob('./dir/*.js')
for (const path in modules) {
const module = await modules[path]()
console.log(path, module)
}
```
### Eager loading
Pass `{ eager: true }` to import all matching modules up front. Each value is the module object directly instead of a thunk:
```js
const modules = import.meta.glob('./dir/*.js', { eager: true })
for (const path in modules) {
console.log(path, modules[path].default)
}
```
### Named imports
Use the `import` option to select a specific named export from each matched module. This works in both lazy and eager modes:
```js
// Lazy: each value is () => Promise<exportValue>
const defaults = import.meta.glob('./dir/*.js', { import: 'default' })
// Eager: each value is the export value directly
const setups = import.meta.glob('./dir/*.js', { import: 'setup', eager: true })
```
### Query strings
Use the `query` option to append a query string to every import request. This is useful for loading files as raw strings or URLs:
```js
const rawFiles = import.meta.glob('./dir/*.txt', { query: '?raw' })
const urls = import.meta.glob('./dir/*.png', { query: '?url' })
```
The `query` option also accepts an object. Keys and values are URL-encoded and joined into a query string:
```js
const modules = import.meta.glob('./*.ts', {
query: { bar: 'foo', raw: true },
})
// equivalent to: { query: '?bar=foo&raw=true' }
```
### Multiple patterns and negation
Pass an array of glob patterns as the first argument. Prefix a pattern with `!` to exclude matching files:
```js
// Combine multiple directories
const modules = import.meta.glob(['./dir/*.js', './other/*.js'])
// Exclude specific files
const withoutTests = import.meta.glob(['./src/**/*.js', '!**/*.test.js'])
```
### TypeScript
TypeScript types for `import.meta.glob` are included in Next.js. They are available automatically when `"moduleResolution": "bundler"` (or `"node16"` / `"nodenext"`) is set in your `tsconfig.json`, which is the default for new Next.js projects.
The return type differs based on the `eager` option:
```ts
// Lazy (default) — Record<string, () => Promise<unknown>>
const lazy = import.meta.glob('./dir/*.ts')
// Eager — Record<string, unknown>
const eager = import.meta.glob('./dir/*.ts', { eager: true })
```
### Options reference
| Option | Type | Default | Description |
| -------- | --------------------------------------------- | ----------- | ---------------------------------------------------------------------- |
| `eager` | `boolean` | `false` | Import modules synchronously instead of returning thunks. |
| `import` | `string` | `undefined` | Named export to select from each matched module (e.g. `'default'`). |
| `query` | `string \| Record<string, string \| boolean>` | `undefined` | Query string (or object) to append to each import. |
| `base` | `string` | `undefined` | Override the base path used for resolving patterns and keying results. |
> **Note:** The `as` option (deprecated in Vite 5) is not supported. Use `query: '?raw'` or `query: '?url'` instead. The legacy `import.meta.globEager()` API is also not supported — use `import.meta.glob('...', { eager: true })` instead.
## Known gaps with webpack
There are a number of non-trivial behavior differences between webpack and Turbopack that are important to be aware of when migrating an application. Generally, these are less of a concern for new applications.
......
......@@ -9,11 +9,6 @@ This documentation explains how you can handle development, server-side, and cli
When there is a runtime error during the development phase of your Next.js application, you will encounter an **overlay**. It is a modal that covers the webpage. It is **only** visible when the development server runs using `next dev` via `pnpm dev`, `npm run dev`, `yarn dev`, or `bun dev` and will not be shown in production. Fixing the error will automatically dismiss the overlay.
Here is an example of an overlay:
{/* TODO UPDATE SCREENSHOT */}
![Example of an overlay when in development mode](https://assets.vercel.com/image/upload/v1645118290/docs-assets/static/docs/error-handling/overlay.png)
## Handling Server Errors
Next.js provides a static 500 page by default to handle server-side errors that occur in your application. You can also [customize this page](/docs/pages/building-your-application/routing/custom-error#customizing-the-500-page) by creating a `pages/500.js` file.
......
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/versions
# 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
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
# VSCode
.vscode
# SuperTokens App with Next.js app directory
This is a simple application that is protected by SuperTokens. This app uses the Next.js app directory.
## How to use
### Using `create-next-app`
- Execute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:
```bash
npx create-next-app --example with-supertokens with-supertokens-app
```
```bash
yarn create next-app --example with-supertokens with-supertokens-app
```
```bash
pnpm create next-app --example with-supertokens with-supertokens-app
```
### Using `create-supertokens-app`
- Run the following command
```bash
npx create-supertokens-app@latest --frontend=next
```
```bash
yarn create-supertokens-app@latest --frontend=next
```
```bash
pnpm create-supertokens-app@latest --frontend=next
```
- Select the option to use the app directory
Follow the instructions after `create-supertokens-app` has finished
## Notes
- To know more about how this app works and to learn how to customise it based on your use cases refer to the [SuperTokens Documentation](https://supertokens.com/docs/guides)
- We have provided development OAuth keys for the various built-in third party providers in the `/app/config/backend.ts` file. Feel free to use them for development purposes, but **please create your own keys for production use**.
import { getAppDirRequestHandler } from "supertokens-node/nextjs";
import { NextRequest, NextResponse } from "next/server";
import { ensureSuperTokensInit } from "../../../config/backend";
ensureSuperTokensInit();
const handleCall = getAppDirRequestHandler(NextResponse);
export async function GET(request: NextRequest) {
const res = await handleCall(request);
if (!res.headers.has("Cache-Control")) {
// This is needed for production deployments with Vercel
res.headers.set(
"Cache-Control",
"no-cache, no-store, max-age=0, must-revalidate",
);
}
return res;
}
export async function POST(request: NextRequest) {
return handleCall(request);
}
export async function DELETE(request: NextRequest) {
return handleCall(request);
}
export async function PUT(request: NextRequest) {
return handleCall(request);
}
export async function PATCH(request: NextRequest) {
return handleCall(request);
}
export async function HEAD(request: NextRequest) {
return handleCall(request);
}
import { ensureSuperTokensInit } from "@/app/config/backend";
import { NextResponse, NextRequest } from "next/server";
import { withSession } from "supertokens-node/nextjs";
ensureSuperTokensInit();
export function GET(request: NextRequest) {
return withSession(request, async (err, session) => {
if (err) {
return NextResponse.json(err, { status: 500 });
}
if (!session) {
return new NextResponse("Authentication required", { status: 401 });
}
return NextResponse.json({
note: "Fetch any data from your application for authenticated user after using verifySession middleware",
userId: session.getUserId(),
sessionHandle: session.getHandle(),
accessTokenPayload: session.getAccessTokenPayload(),
});
});
}
"use client";
import { useEffect, useState } from "react";
import { redirectToAuth } from "supertokens-auth-react";
import SuperTokens from "supertokens-auth-react/ui";
import { PreBuiltUIList } from "../../config/frontend";
export default function Auth() {
// if the user visits a page that is not handled by us (like /auth/random), then we redirect them back to the auth page.
const [loaded, setLoaded] = useState(false);
useEffect(() => {
if (SuperTokens.canHandleRoute(PreBuiltUIList) === false) {
redirectToAuth({ redirectBack: false });
} else {
setLoaded(true);
}
}, []);
if (loaded) {
return SuperTokens.getRoutingComponent(PreBuiltUIList);
}
return null;
}
"use client";
import styles from "../page.module.css";
export const CallAPIButton = () => {
const fetchUserData = async () => {
const userInfoResponse = await fetch("http://localhost:3000/api/user");
alert(JSON.stringify(await userInfoResponse.json()));
};
return (
<div onClick={fetchUserData} className={styles.sessionButton}>
Call API
</div>
);
};
import { cookies } from "next/headers";
import { TryRefreshComponent } from "./tryRefreshClientComponent";
import styles from "../page.module.css";
import { redirect } from "next/navigation";
import Image from "next/image";
import { CelebrateIcon, SeparatorLine } from "../../assets/images";
import { CallAPIButton } from "./callApiButton";
import { LinksComponent } from "./linksComponent";
import { SessionAuthForNextJS } from "./sessionAuthForNextJS";
import jwksClient from "jwks-rsa";
import JsonWebToken from "jsonwebtoken";
import type { JwtHeader, JwtPayload, SigningKeyCallback } from "jsonwebtoken";
import { appInfo } from "../config/appInfo";
const client = jwksClient({
jwksUri: `${appInfo.apiDomain}${appInfo.apiBasePath}/jwt/jwks.json`,
});
function getAccessToken(): string | undefined {
return cookies().get("sAccessToken")?.value;
}
function getPublicKey(header: JwtHeader, callback: SigningKeyCallback) {
client.getSigningKey(header.kid, (err, key) => {
if (err) {
callback(err);
} else {
const signingKey = key?.getPublicKey();
callback(null, signingKey);
}
});
}
async function verifyToken(token: string): Promise<JwtPayload> {
return new Promise((resolve, reject) => {
JsonWebToken.verify(token, getPublicKey, {}, (err, decoded) => {
if (err) {
reject(err);
} else {
resolve(decoded as JwtPayload);
}
});
});
}
/**
* A helper function to retrieve session details on the server side.
*
* NOTE: This function does not use the getSSRSession function from the supertokens-node SDK
* because getSession can update the access token. These updated tokens would not be
* propagated to the client side, as request interceptors do not run on the server side.
*/
async function getSSRSessionHelper(): Promise<{
accessTokenPayload: JwtPayload | undefined;
hasToken: boolean;
error: Error | undefined;
}> {
const accessToken = getAccessToken();
const hasToken = !!accessToken;
try {
if (accessToken) {
const decoded = await verifyToken(accessToken);
return { accessTokenPayload: decoded, hasToken, error: undefined };
}
return { accessTokenPayload: undefined, hasToken, error: undefined };
} catch (error) {
if (error instanceof JsonWebToken.TokenExpiredError) {
return { accessTokenPayload: undefined, hasToken, error: undefined };
}
return { accessTokenPayload: undefined, hasToken, error: error as Error };
}
}
export async function HomePage() {
const { accessTokenPayload, hasToken, error } = await getSSRSessionHelper();
if (error) {
return (
<div>
Something went wrong while trying to get the session. Error -{" "}
{error.message}
</div>
);
}
// `accessTokenPayload` will be undefined if it the session does not exist or has expired
if (accessTokenPayload === undefined) {
if (!hasToken) {
/**
* This means that the user is not logged in. If you want to display some other UI in this
* case, you can do so here.
*/
return redirect("/auth");
}
/**
* This means that the session does not exist but we have session tokens for the user. In this case
* the `TryRefreshComponent` will try to refresh the session.
*
* To learn about why the 'key' attribute is required refer to: https://github.com/supertokens/supertokens-node/issues/826#issuecomment-2092144048
*/
return <TryRefreshComponent key={Date.now()} />;
}
/**
* SessionAuthForNextJS will handle proper redirection for the user based on the different session states.
* It will redirect to the login page if the session does not exist etc.
*/
return (
<SessionAuthForNextJS>
<div className={styles.homeContainer}>
<div className={styles.mainContainer}>
<div
className={`${styles.topBand} ${styles.successTitle} ${styles.bold500}`}
>
<Image
src={CelebrateIcon}
alt="Login successful"
className={styles.successIcon}
/>{" "}
Login successful
</div>
<div className={styles.innerContent}>
<div>Your userID is:</div>
<div className={`${styles.truncate} ${styles.userId}`}>
{accessTokenPayload.sub}
</div>
<CallAPIButton />
</div>
</div>
<LinksComponent />
<Image
className={styles.separatorLine}
src={SeparatorLine}
alt="separator"
/>
</div>
</SessionAuthForNextJS>
);
}
"use client";
import styles from "../page.module.css";
import { BlogsIcon, GuideIcon, SignOutIcon } from "../../assets/images";
import { recipeDetails } from "../config/frontend";
import Link from "next/link";
import Image from "next/image";
import Session from "supertokens-auth-react/recipe/session";
import SuperTokens from "supertokens-auth-react";
const SignOutLink = (props: { name: string; link: string; icon: string }) => {
return (
<div
className={styles.linksContainerLink}
onClick={async () => {
await Session.signOut();
SuperTokens.redirectToAuth();
}}
>
<Image className={styles.linkIcon} src={props.icon} alt={props.name} />
<div role={"button"}>{props.name}</div>
</div>
);
};
export const LinksComponent = () => {
const links: {
name: string;
link: string;
icon: string;
}[] = [
{
name: "Blogs",
link: "https://supertokens.com/blog",
icon: BlogsIcon,
},
{
name: "Guides",
link: recipeDetails.docsLink,
icon: GuideIcon,
},
{
name: "Sign Out",
link: "",
icon: SignOutIcon,
},
];
return (
<div className={styles.bottomLinksContainer}>
{links.map((link) => {
if (link.name === "Sign Out") {
return (
<SignOutLink
name={link.name}
link={link.link}
icon={link.icon}
key={link.name}
/>
);
}
return (
<Link
href={link.link}
className={styles.linksContainerLink}
key={link.name}
target="_blank"
>
<Image
className={styles.linkIcon}
src={link.icon}
alt={link.name}
/>
<div role={"button"}>{link.name}</div>
</Link>
);
})}
</div>
);
};
"use client";
import React, { useState, useEffect } from "react";
import { SessionAuth } from "supertokens-auth-react/recipe/session";
type Props = Parameters<typeof SessionAuth>[0] & {
children?: React.ReactNode | undefined;
};
export const SessionAuthForNextJS = (props: Props) => {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
setLoaded(true);
}, []);
if (!loaded) {
return props.children;
}
return <SessionAuth {...props}>{props.children}</SessionAuth>;
};
"use client";
import React from "react";
import { SuperTokensWrapper } from "supertokens-auth-react";
import SuperTokensReact from "supertokens-auth-react";
import { frontendConfig, setRouter } from "../config/frontend";
import { usePathname, useRouter } from "next/navigation";
if (typeof window !== "undefined") {
// we only want to call this init function on the frontend, so we check typeof window !== 'undefined'
SuperTokensReact.init(frontendConfig());
}
export const SuperTokensProvider: React.FC<React.PropsWithChildren<{}>> = ({
children,
}) => {
setRouter(useRouter(), usePathname() || window.location.pathname);
return <SuperTokensWrapper>{children}</SuperTokensWrapper>;
};
"use client";
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import Session from "supertokens-auth-react/recipe/session";
import SuperTokens from "supertokens-auth-react";
export const TryRefreshComponent = () => {
const router = useRouter();
const [didError, setDidError] = useState(false);
useEffect(() => {
void Session.attemptRefreshingSession()
.then((hasSession) => {
if (hasSession) {
router.refresh();
} else {
SuperTokens.redirectToAuth();
}
})
.catch(() => {
setDidError(true);
});
}, [router]);
if (didError) {
return <div>Something went wrong, please reload the page</div>;
}
return <div>Loading...</div>;
};
export const appInfo = {
appName: "SuperTokens Next.js demo app",
apiDomain: "http://localhost:3000",
websiteDomain: "http://localhost:3000",
apiBasePath: "/api/auth",
websiteBasePath: "/auth",
};
import ThirdPartyNode from "supertokens-node/recipe/thirdparty";
import EmailPasswordNode from "supertokens-node/recipe/emailpassword";
import SessionNode from "supertokens-node/recipe/session";
import Dashboard from "supertokens-node/recipe/dashboard";
import UserRoles from "supertokens-node/recipe/userroles";
import { appInfo } from "./appInfo";
import { TypeInput } from "supertokens-node/types";
import SuperTokens from "supertokens-node";
export let backendConfig = (): TypeInput => {
return {
supertokens: {
// this is the location of the SuperTokens core.
connectionURI: "https://try.supertokens.com",
},
appInfo,
// recipeList contains all the modules that you want to
// use from SuperTokens. See the full list here: https://supertokens.com/docs/guides
recipeList: [
EmailPasswordNode.init(),
ThirdPartyNode.init({
signInAndUpFeature: {
providers: [
// We have provided you with development keys which you can use for testing.
// IMPORTANT: Please replace them with your own OAuth keys for production use.
{
config: {
thirdPartyId: "google",
clients: [
{
clientId:
"1060725074195-kmeum4crr01uirfl2op9kd5acmi9jutn.apps.googleusercontent.com",
clientSecret: "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",
},
],
},
},
{
config: {
thirdPartyId: "github",
clients: [
{
clientId: "467101b197249757c71f",
clientSecret: "e97051221f4b6426e8fe8d51486396703012f5bd",
},
],
},
},
{
config: {
thirdPartyId: "apple",
clients: [
{
clientId: "4398792-io.supertokens.example.service",
additionalConfig: {
keyId: "7M48Y4RYDL",
privateKey:
"-----BEGIN PRIVATE KEY-----\nMIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgu8gXs+XYkqXD6Ala9Sf/iJXzhbwcoG5dMh1OonpdJUmgCgYIKoZIzj0DAQehRANCAASfrvlFbFCYqn3I2zeknYXLwtH30JuOKestDbSfZYxZNMqhF/OzdZFTV0zc5u5s3eN+oCWbnvl0hM+9IW0UlkdA\n-----END PRIVATE KEY-----",
teamId: "YWQCXGJRJL",
},
},
],
},
},
{
config: {
thirdPartyId: "twitter",
clients: [
{
clientId: "4398792-WXpqVXRiazdRMGNJdEZIa3RVQXc6MTpjaQ",
clientSecret:
"BivMbtwmcygbRLNQ0zk45yxvW246tnYnTFFq-LH39NwZMxFpdC",
},
],
},
},
],
},
}),
SessionNode.init(),
Dashboard.init(),
UserRoles.init(),
],
isInServerlessEnv: true,
framework: "custom",
};
};
let initialized = false;
export function ensureSuperTokensInit() {
if (!initialized) {
SuperTokens.init(backendConfig());
initialized = true;
}
}
import ThirdPartyReact from "supertokens-auth-react/recipe/thirdparty";
import EmailPasswordReact from "supertokens-auth-react/recipe/emailpassword";
import Session from "supertokens-auth-react/recipe/session";
import { appInfo } from "./appInfo";
import { type useRouter } from "next/navigation";
import { SuperTokensConfig } from "supertokens-auth-react/lib/build/types";
import { ThirdPartyPreBuiltUI } from "supertokens-auth-react/recipe/thirdparty/prebuiltui";
import { EmailPasswordPreBuiltUI } from "supertokens-auth-react/recipe/emailpassword/prebuiltui";
const routerInfo: { router?: ReturnType<typeof useRouter>; pathname?: string } =
{};
export function setRouter(
router: ReturnType<typeof useRouter>,
pathname: string,
) {
routerInfo.router = router;
routerInfo.pathname = pathname;
}
export const frontendConfig = (): SuperTokensConfig => {
return {
appInfo,
recipeList: [
EmailPasswordReact.init(),
ThirdPartyReact.init({
signInAndUpFeature: {
providers: [
ThirdPartyReact.Google.init(),
ThirdPartyReact.Github.init(),
ThirdPartyReact.Apple.init(),
],
},
}),
Session.init(),
],
windowHandler: (orig) => {
return {
...orig,
location: {
...orig.location,
getPathname: () => routerInfo.pathname!,
assign: (url) => routerInfo.router!.push(url.toString()),
setHref: (url) => routerInfo.router!.push(url.toString()),
},
};
},
};
};
export const recipeDetails = {
docsLink: "https://supertokens.com/docs/thirdpartyemailpassword/introduction",
};
export const PreBuiltUIList = [ThirdPartyPreBuiltUI, EmailPasswordPreBuiltUI];
import "./globals.css";
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import { SuperTokensProvider } from "./components/supertokensProvider";
const inter = Inter({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "SuperTokens 💫",
description: "SuperTokens demo app",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<body className={inter.className}>
<SuperTokensProvider>{children}</SuperTokensProvider>
</body>
</html>
);
}
.main {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
}
@font-face {
font-family: Menlo;
src: url("../assets/fonts/MenloRegular.ttf");
}
.appContainer {
font-family: Rubik, sans-serif;
}
.appContainer * {
box-sizing: border-box;
}
.bold400 {
font-variation-settings: "wght" 400;
}
.bold500 {
font-variation-settings: "wght" 500;
}
.bold600 {
font-variation-settings: "wght" 600;
}
.homeContainer {
min-height: 100vh;
min-width: 100vw;
background: url("../assets/images/background.png");
background-size: cover;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.bold700 {
font-variation-settings: "wght" 700;
}
.mainContainer {
box-shadow: 0px 0px 60px 0px rgba(0, 0, 0, 0.16);
width: min(635px, calc(100% - 24px));
border-radius: 16px;
margin-block-end: 159px;
background-color: #ffffff;
}
.successTitle {
line-height: 1;
padding-block: 26px;
background-color: #e7ffed;
text-align: center;
color: #3eb655;
display: flex;
justify-content: center;
align-items: flex-end;
font-size: 20px;
}
.successIcon {
margin-right: 8px;
}
.innerContent {
padding-block: 48px;
text-align: center;
display: flex;
flex-direction: column;
align-items: center;
}
.userId {
position: relative;
padding: 14px 17px;
border-image-slice: 1;
width: min(430px, calc(100% - 30px));
margin-inline: auto;
margin-block: 11px 23px;
border-radius: 9px;
line-height: 1;
font-family: Menlo, serif;
cursor: text;
}
.userId:before {
content: "";
position: absolute;
inset: 0;
border-radius: 9px;
padding: 2px;
background: linear-gradient(90.31deg, #ff9933 0.11%, #ff3f33 99.82%);
mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
-webkit-mask:
linear-gradient(#fff 0 0) content-box,
linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
}
.topBand,
.bottomBand {
border-radius: inherit;
}
.topBand {
border-bottom-left-radius: 0;
border-bottom-right-radius: 0;
}
.bottomBand {
border-top-left-radius: 0;
border-top-right-radius: 0;
}
.sessionButton {
padding-left: 13px;
padding-right: 13px;
padding-top: 8px;
padding-bottom: 8px;
cursor: pointer;
color: white;
font-weight: bold;
font-size: 17px;
box-sizing: border-box;
background: #ff9933;
border: 1px solid #ff8a15;
box-shadow: 0px 3px 6px rgba(255, 153, 51, 0.16);
border-radius: 6px;
font-size: 16px;
}
.bottomCTAContainer {
display: flex;
justify-content: flex-end;
padding-inline: 21px;
background-color: #212d4f;
}
.viewCode {
padding-block: 11px;
color: #bac9f5;
cursor: pointer;
font-size: 14px;
}
.bottomLinksContainer {
display: grid;
grid-template-columns: repeat(4, auto);
margin-bottom: 22px;
}
.linksContainerLink {
display: flex;
align-items: center;
margin-inline-end: 68px;
cursor: pointer;
text-decoration: none;
color: #000000;
}
.linksContainerLink:last-child {
margin-right: 0;
}
.truncate {
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap;
}
.separatorLine {
max-width: 100%;
}
.linkIcon {
width: 15px;
margin-right: 5px;
}
@media screen and (max-width: 768px) {
.bottomLinksContainer {
grid-template-columns: repeat(2, 1fr);
column-gap: 64px;
row-gap: 34px;
}
.linksContainerLink {
margin-inline-end: 0;
}
.separatorLine {
max-width: 200px;
}
}
@media screen and (max-width: 480px) {
.homeContainer {
justify-content: start;
padding-block-start: 25px;
}
.mainContainer {
margin-block-end: 90px;
}
}
import { HomePage } from "./components/home";
import styles from "./page.module.css";
export default function Home() {
return (
<main className={styles.main}>
<HomePage />
</main>
);
}
<svg width="13" height="11" viewBox="0 0 13 11" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M1.64867 6.69299H1.63067L9.34667 6.69299L6.92167 9.12099C6.80247 9.24042 6.73553 9.40226 6.73553 9.57099C6.73553 9.73973 6.80247 9.90157 6.92167 10.021L7.29867 10.394C7.41695 10.5119 7.57716 10.5781 7.74417 10.5781C7.91119 10.5781 8.07139 10.5119 8.18967 10.394L12.3477 6.23699C12.4653 6.11795 12.5312 5.95734 12.5312 5.78999C12.5312 5.62264 12.4653 5.46204 12.3477 5.34299L8.18967 1.18399C8.07127 1.06632 7.91111 1.00027 7.74417 1.00027C7.57724 1.00027 7.41708 1.06632 7.29867 1.18399L6.92167 1.56199C6.8631 1.62031 6.81668 1.68968 6.7851 1.76606C6.75351 1.84245 6.73739 1.92434 6.73767 2.00699C6.73739 2.08846 6.75354 2.16915 6.78516 2.24424C6.81677 2.31932 6.8632 2.38726 6.92167 2.44399L9.37467 4.88899L1.64067 4.88899C1.47078 4.89237 1.3089 4.96184 1.1894 5.08264C1.0699 5.20345 1.0022 5.36608 1.00067 5.53599V6.06999C1.00538 6.23808 1.07595 6.39758 1.19717 6.51412C1.31838 6.63065 1.48053 6.6949 1.64867 6.69299Z" fill="#BAC9F5" stroke="#212D4F" stroke-width="0.5"/>
</svg>
<svg width="16" height="14" viewBox="0 0 16 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M1.34272 0.0267221C0.710774 0.121007 0.1734 0.636512 0.0398429 1.27659C0.0170474 1.38568 4.32967e-06 1.82922 4.32967e-06 2.31199V3.15656H7.3467H14.6934L14.676 2.2292C14.6608 1.4129 14.6499 1.27745 14.5856 1.09832C14.4153 0.624123 14.0643 0.263154 13.6055 0.0903228L13.3808 0.00568978L7.4675 0.000431738C4.21521 -0.00244938 1.45906 0.00939935 1.34272 0.0267221ZM2.48986 1.21C2.63421 1.2987 2.69163 1.40714 2.69163 1.59088C2.69163 2.09198 2.00379 2.2091 1.826 1.73829C1.67873 1.34826 2.13021 0.988981 2.48986 1.21ZM4.07175 1.19869C4.20817 1.2799 4.28756 1.4294 4.28756 1.60504C4.28756 1.72183 4.26305 1.78003 4.1714 1.8808C3.96214 2.11096 3.62788 2.07916 3.46224 1.81327C3.28874 1.53481 3.50208 1.13977 3.82597 1.13977C3.90675 1.13977 4.01734 1.16628 4.07175 1.19869ZM5.75855 1.27893C5.89057 1.42785 5.91765 1.55303 5.85627 1.73051C5.69074 2.20928 4.9988 2.09072 5.0034 1.5844C5.00601 1.29913 5.19699 1.12645 5.4824 1.15122C5.62453 1.16354 5.6783 1.18843 5.75855 1.27893ZM4.32967e-06 7.63267C4.32967e-06 11.5161 -0.00342567 11.4373 0.182797 11.81C0.364983 12.1746 0.689158 12.4502 1.10005 12.5896C1.31829 12.6638 1.35927 12.6645 4.66901 12.6554L8.01716 12.6463L8.09999 12.1637C8.23997 11.3484 8.02109 11.6174 10.8909 8.73304C13.2137 6.39832 13.4356 6.18527 13.6543 6.07949C13.8927 5.96421 14.1971 5.87907 14.5158 5.83863L14.6861 5.81699L14.6766 4.92794L14.667 4.0389L7.33351 4.02983L4.32967e-06 4.02071V7.63267ZM14.4223 6.72371C14.1115 6.77629 13.9052 6.91088 13.4884 7.33303L13.0958 7.7307L14.0418 8.68471L14.9878 9.63876L15.3738 9.25175C15.8333 8.79117 15.9626 8.56748 15.9951 8.17659C16.0545 7.462 15.5678 6.83964 14.8589 6.72371C14.7337 6.70322 14.6233 6.68827 14.6134 6.69043C14.6036 6.69263 14.5176 6.70758 14.4223 6.72371ZM10.7681 10.0802C9.82255 11.036 9.03878 11.8476 9.02642 11.8838C8.96561 12.062 8.75041 13.4915 8.76602 13.6137C8.77688 13.6988 8.82219 13.7931 8.88286 13.857C9.05847 14.0417 9.13779 14.0436 10.0484 13.885C10.5017 13.806 10.8984 13.7269 10.9298 13.7092C10.9612 13.6916 11.7506 12.9063 12.6839 11.9642L14.381 10.2512L13.4341 9.29688L12.4873 8.3425L10.7681 10.0802Z" fill="#212D4F"/>
</svg>
<svg width="13" height="14" viewBox="0 0 13 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M1.85572 0.029056C0.990534 0.169641 0.278576 0.818617 0.0594541 1.6664C0.00119265 1.89188 0 1.99774 0 7.00566C0 12.0136 0.00119265 12.1194 0.0594541 12.3449C0.260268 13.1218 0.869688 13.7282 1.66972 13.947C1.85396 13.9974 2.12723 14 7.20069 14C12.1136 14 12.545 13.9962 12.6279 13.9518C12.8578 13.8288 12.9983 13.602 12.9993 13.352C13.0004 13.0979 12.8691 12.8809 12.65 12.7747C12.5421 12.7224 12.339 12.7198 7.27523 12.7058L2.01261 12.6913L1.86353 12.6193C1.4467 12.4181 1.24302 11.9518 1.38921 11.5333C1.44667 11.3688 1.66284 11.1268 1.83035 11.0394L1.95298 10.9754L7.2156 10.9609C12.2043 10.9471 12.4844 10.9436 12.5975 10.8939C12.755 10.8246 12.8757 10.7111 12.9435 10.5683C12.9965 10.4565 12.9987 10.2573 12.9993 5.47726L13 0.502606L12.9245 0.354751C12.8438 0.196862 12.6923 0.0732324 12.5206 0.0251881C12.3918 -0.0108161 2.07812 -0.00706442 1.85572 0.029056ZM6.92972 2.01798C7.92323 2.22327 8.63441 3.19061 8.50125 4.1556C8.41473 4.78279 8.08877 5.28453 7.54921 5.62104C7.36507 5.73589 7.31998 5.78056 7.2588 5.90875C7.2147 6.00109 7.18626 6.11399 7.18608 6.19719C7.1853 6.56404 7.04934 6.81656 6.78892 6.93481C6.5825 7.02855 6.40614 7.0268 6.20497 6.92903C5.89365 6.77771 5.78721 6.51536 5.84213 6.03485C5.91971 5.35619 6.23085 4.88019 6.84527 4.50011C7.28832 4.22607 7.26432 3.60007 6.80171 3.36432C6.58832 3.25559 6.41168 3.25559 6.19829 3.36432C5.94186 3.49499 5.87612 3.61653 5.79967 4.10125C5.77412 4.26341 5.62602 4.43974 5.44718 4.52096C5.09609 4.68042 4.73641 4.56284 4.55197 4.22828C4.50065 4.13521 4.48837 4.06539 4.49052 3.87929C4.49904 3.14708 4.94313 2.48932 5.65238 2.15845C6.03131 1.98168 6.50301 1.9298 6.92972 2.01798ZM6.71698 7.70538C6.77893 7.72216 6.877 7.77646 6.9349 7.82608C7.3354 8.16905 7.19323 8.79929 6.68275 8.94404C6.12264 9.10286 5.64173 8.53351 5.90525 8.02355C6.05096 7.74153 6.37769 7.61348 6.71698 7.70538Z" fill="#212D4F"/>
</svg>
import SeparatorLine from "./separator-line.svg";
import ArrowRight from "./arrow-right-icon.svg";
import SignOutIcon from "./sign-out-icon.svg";
import GuideIcon from "./guide-icon.svg";
import BlogsIcon from "./blogs-icon.svg";
import CelebrateIcon from "./celebrate-icon.svg";
export {
SeparatorLine,
ArrowRight,
SignOutIcon,
GuideIcon,
BlogsIcon,
CelebrateIcon,
};
<svg width="530" height="1" viewBox="0 0 530 1" fill="none" xmlns="http://www.w3.org/2000/svg">
<line opacity="0.2" x1="0.5" y1="0.5" x2="529.5" y2="0.5" stroke="url(#paint0_linear_2144_48022)" stroke-linecap="round"/>
<defs>
<linearGradient id="paint0_linear_2144_48022" x1="530" y1="1.00041" x2="0" y2="1" gradientUnits="userSpaceOnUse">
<stop stop-color="white"/>
<stop offset="0.503472" stop-color="#212D4F"/>
<stop offset="1" stop-color="white"/>
</linearGradient>
</defs>
</svg>
<svg width="15" height="15" viewBox="0 0 15 15" fill="none" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" clip-rule="evenodd" d="M0.952012 0.0390744C0.51903 0.146482 0.157855 0.50616 0.0407246 0.946584C0.00735517 1.07209 0.000499641 2.07489 0.000206669 6.87688C-0.000174194 13.2011 -0.00998874 12.8335 0.167464 13.1368C0.273959 13.3187 0.492574 13.53 0.662527 13.6151C0.74119 13.6546 1.68884 13.9823 2.76844 14.3434L4.73134 15L4.99502 14.9999C5.3179 14.9999 5.49858 14.9427 5.74139 14.7638C5.93903 14.6181 6.09518 14.4027 6.18161 14.1565C6.2298 14.0193 6.24015 13.9145 6.24015 13.5638V13.1377L7.27287 13.1372C8.45281 13.1366 8.57006 13.1222 8.96478 12.9288C9.43884 12.6964 9.82421 12.2134 9.94456 11.7005C10.0116 11.4151 10.0118 8.67078 9.94483 8.51034C9.74871 8.04041 9.07069 8.00974 8.82284 8.45954C8.78018 8.53695 8.77259 8.72038 8.7597 9.98472L8.74505 11.4219L8.67181 11.5526C8.63153 11.6245 8.54141 11.7235 8.47156 11.7726L8.34459 11.8619L7.2927 11.8702L6.24082 11.8786L6.23317 7.03075L6.2255 2.18286L6.13277 1.98693C5.98002 1.66412 5.77456 1.47327 5.42299 1.32758L5.25869 1.25951L6.80163 1.26658L8.34456 1.27362L8.47156 1.3629C8.54141 1.41203 8.63153 1.51102 8.67181 1.58288L8.74505 1.71357L8.7597 2.84769L8.77435 3.98177L8.86224 4.10663C8.99411 4.29394 9.16711 4.37498 9.40781 4.36213C9.631 4.35025 9.77868 4.26736 9.90229 4.08466L9.97553 3.97638L9.98382 2.8097C9.99314 1.49782 9.98435 1.41625 9.7919 1.02431C9.63372 0.702204 9.2973 0.369686 8.96478 0.206726C8.51943 -0.0115204 8.72768 -0.00146014 4.70205 0.000739632C1.94032 0.00226481 1.06428 0.0112399 0.952012 0.0390744ZM11.6159 3.19079C11.4682 3.25796 11.321 3.42373 11.281 3.56792C11.2624 3.63494 11.2502 4.06393 11.2501 4.65394L11.25 5.62917H9.93733H8.62473L8.47051 5.7061C8.20678 5.83768 8.07816 6.11511 8.14724 6.40343C8.19459 6.60094 8.39642 6.80702 8.59039 6.85591C8.68452 6.87964 9.11956 6.89037 9.98851 6.89037H11.25V7.8622C11.25 8.54619 11.2606 8.86979 11.286 8.95476C11.3571 9.19289 11.631 9.38453 11.8979 9.3828C12.1309 9.38128 12.2108 9.31314 13.5579 7.96682C14.9082 6.61737 15 6.50993 15 6.27942C15 6.00272 15.0163 6.02234 13.5962 4.59442C12.7161 3.70956 12.2201 3.232 12.1416 3.1939C11.992 3.12131 11.7716 3.11999 11.6159 3.19079Z" fill="#212D4F"/>
</svg>
import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { SessionContainer } from "supertokens-node/recipe/session";
import { withSession } from "supertokens-node/nextjs";
import { ensureSuperTokensInit } from "./app/config/backend";
ensureSuperTokensInit();
export async function middleware(
request: NextRequest & { session?: SessionContainer },
) {
if (request.headers.has("x-user-id")) {
console.warn(
"The FE tried to pass x-user-id, which is only supposed to be a backend internal header. Ignoring.",
);
request.headers.delete("x-user-id");
}
if (request.nextUrl.pathname.startsWith("/api/auth")) {
// this hits our pages/api/auth/* endpoints
return NextResponse.next();
}
return withSession(request, async (err, session) => {
if (err) {
return NextResponse.json(err, { status: 500 });
}
if (session === undefined) {
return NextResponse.next();
}
return NextResponse.next({
headers: {
"x-user-id": session.getUserId(),
},
});
});
}
export const config = {
matcher: "/api/:path*",
};
/** @type {import('next').NextConfig} */
const nextConfig = {};
module.exports = nextConfig;
{
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint ."
},
"dependencies": {
"jsonwebtoken": "^9.0.2",
"jwks-rsa": "^3.1.0",
"next": "latest",
"react": "^18",
"react-dom": "^18",
"supertokens-auth-react": "latest",
"supertokens-node": "latest"
},
"devDependencies": {
"@types/cookie": "^0.5.2",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
"eslint": "^9",
"eslint-config-next": "13.5.4",
"typescript": "^5"
}
}
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>
\ No newline at end of file
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 283 64"><path fill="black" d="M141 16c-11 0-19 7-19 18s9 18 20 18c7 0 13-3 16-7l-7-5c-2 3-6 4-9 4-5 0-9-3-10-7h28v-3c0-11-8-18-19-18zm-9 15c1-4 4-7 9-7s8 3 9 7h-18zm117-15c-11 0-19 7-19 18s9 18 20 18c6 0 12-3 16-7l-8-5c-2 3-5 4-8 4-5 0-9-3-11-7h28l1-3c0-11-8-18-19-18zm-10 15c2-4 5-7 10-7s8 3 9 7h-19zm-39 3c0 6 4 10 10 10 4 0 7-2 9-5l8 5c-3 5-9 8-17 8-11 0-19-7-19-18s8-18 19-18c8 0 14 3 17 8l-8 5c-2-3-5-5-9-5-6 0-10 4-10 10zm83-29v46h-9V5h9zM37 0l37 64H0L37 0zm92 5-27 48L74 5h10l18 30 17-30h10zm59 12v10l-3-1c-6 0-10 4-10 10v15h-9V17h9v9c0-5 6-9 13-9z"/></svg>
\ No newline at end of file
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
......@@ -15,5 +15,5 @@
"registry": "https://registry.npmjs.org/"
}
},
"version": "16.3.0-canary.2"
}
\ No newline at end of file
"version": "16.3.0-canary.4"
}
This diff is collapsed.
{
"name": "create-next-app",
"version": "16.3.0-canary.2",
"version": "16.3.0-canary.4",
"keywords": [
"react",
"next",
......@@ -41,7 +41,6 @@
"cross-spawn": "7.0.3",
"fast-glob": "3.3.1",
"picocolors": "1.1.1",
"prettier": "catalog:",
"prettier-plugin-tailwindcss": "0.6.2",
"prompts": "2.4.2",
"tar": "7.5.7",
......
{
"name": "eslint-config-next",
"version": "16.3.0-canary.2",
"version": "16.3.0-canary.4",
"description": "ESLint configuration used by Next.js.",
"license": "MIT",
"repository": {
......@@ -12,7 +12,7 @@
"dist"
],
"dependencies": {
"@next/eslint-plugin-next": "16.3.0-canary.2",
"@next/eslint-plugin-next": "16.3.0-canary.4",
"eslint-import-resolver-node": "^0.3.6",
"eslint-import-resolver-typescript": "^3.5.2",
"eslint-plugin-import": "^2.32.0",
......
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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