Unverified Commit 846b46fd authored by Arindam Majumder's avatar Arindam Majumder Committed by GitHub

Add --api Flag to Create Headless API App with create-next-app (#68130)

### What?

Added a new option for `create-next-app` to create a headless API app.
This includes:
- Adding a `--api` flag for `create-next-app` to create a headless app.
- Modifying the template to include only the required assets (no
`public/`, `app/page.*`, etc.).
- Ensuring the app includes only the required dependencies (no
`@types/react`, `react`, etc.).

### Why?

This feature allows users to initialize projects with headless API
templates, making it easier to set up projects that require backend
functionality without frontend components.

### How?

- Added the `--api` flag to the `create-next-app` command.
- Modified the template to exclude unnecessary assets and dependencies.
- Included exemplary usage of `route.js` features with comments for user
guidance.
- Implemented HTTP Methods and Parameters for request validation.

Closes #68118
Closes NEXT-3633
Closes NDX-120

---------
Signed-off-by: 's avatarArindam Majumder <arindammajumder2020@gmail.com>
Co-authored-by: 's avatarMert Can Altin <mertgold60@gmail.com>
Co-authored-by: 's avatarJiwon Choi <devjiwonchoi@gmail.com>
Co-authored-by: 's avatarTim_Z <z22zhong@uwaterloo.ca>
Co-authored-by: 's avatarTim_Z <43297139+Tim-Zj@users.noreply.github.com>
Co-authored-by: 's avatarAhmed Abdelbaset <A7med3bdulBaset@gmail.com>
Co-authored-by: 's avatarLee Robinson <me@leerob.io>
Co-authored-by: 's avatarEphraim Atta-Duncan <ephraimduncan68@gmail.com>
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
parent 7da911d6
......@@ -36,6 +36,7 @@ export async function createApp({
importAlias,
skipInstall,
empty,
api,
turbopack,
disableGit,
}: {
......@@ -51,6 +52,7 @@ export async function createApp({
importAlias: string
skipInstall: boolean
empty: boolean
api?: boolean
turbopack: boolean
disableGit?: boolean
}): Promise<void> {
......@@ -224,7 +226,7 @@ export async function createApp({
await installTemplate({
appName,
root,
template,
template: api ? 'app-api' : template,
mode,
packageManager,
isOnline,
......
......@@ -57,6 +57,7 @@ const program = new Command(packageJson.name)
'--import-alias <prefix/*>',
'Specify import alias to use (default "@/*").'
)
.option('--api', 'Initialize a headless API using the App Router.')
.option('--empty', 'Initialize an empty project.')
.option(
'--use-npm',
......@@ -275,7 +276,7 @@ async function run(): Promise<void> {
}
}
if (!opts.eslint && !args.includes('--no-eslint')) {
if (!opts.eslint && !args.includes('--no-eslint') && !opts.api) {
if (skipPrompt) {
opts.eslint = getPrefOrDefault('eslint')
} else {
......@@ -294,7 +295,7 @@ async function run(): Promise<void> {
}
}
if (!opts.tailwind && !args.includes('--no-tailwind')) {
if (!opts.tailwind && !args.includes('--no-tailwind') && !opts.api) {
if (skipPrompt) {
opts.tailwind = getPrefOrDefault('tailwind')
} else {
......@@ -332,7 +333,7 @@ async function run(): Promise<void> {
}
}
if (!opts.app && !args.includes('--no-app')) {
if (!opts.app && !args.includes('--no-app') && !opts.api) {
if (skipPrompt) {
opts.app = getPrefOrDefault('app')
} else {
......@@ -429,6 +430,7 @@ async function run(): Promise<void> {
importAlias: opts.importAlias,
skipInstall: opts.skipInstall,
empty: opts.empty,
api: opts.api,
turbopack: opts.turbopack,
disableGit: opts.disableGit,
})
......
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/route.ts`. The page auto-updates as you edit the file.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
## API Routes
This directory contains example API routes for the headless API app.
For more details, see [route.js file convention](https://nextjs.org/docs/app/api-reference/file-conventions/route).
import { NextResponse } from "next/server";
export async function GET(request, { params }) {
const { slug } = await params;
return NextResponse.json({ message: `Hello ${slug}!` });
}
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ message: "Hello world!" });
}
# 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
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}
/** @type {import('next').NextConfig} */
const nextConfig = {};
export default nextConfig;
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/create-next-app).
## Getting Started
First, run the development server:
```bash
npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result.
You can start editing the page by modifying `app/route.ts`. The page auto-updates as you edit the file.
## Learn More
To learn more about Next.js, take a look at the following resources:
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API.
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial.
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome!
## Deploy on Vercel
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js.
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details.
## API Routes
This directory contains example API routes for the headless API app.
For more details, see [route.js file convention](https://nextjs.org/docs/app/api-reference/file-conventions/route).
import { NextRequest, NextResponse } from "next/server";
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ slug: string }> },
) {
const { slug } = await params;
return NextResponse.json({ message: `Hello ${slug}!` });
}
import { NextResponse } from "next/server";
export async function GET() {
return NextResponse.json({ message: "Hello world!" });
}
# 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*
# env files (can opt-in for commiting if needed)
.env*
# vercel
.vercel
# typescript
*.tsbuildinfo
next-env.d.ts
/// <reference types="next" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
/* config options here */
};
export default nextConfig;
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
......@@ -51,6 +51,7 @@ export const installTemplate = async ({
* Copy the template files to the target directory.
*/
console.log("\nInitializing project with template:", template, "\n");
const isApi = template === "app-api";
const templatePath = path.join(__dirname, template, mode);
const copySource = ["**"];
if (!eslint) copySource.push("!eslint.config.mjs");
......@@ -146,35 +147,37 @@ export const installTemplate = async ({
}),
);
const isAppTemplate = template.startsWith("app");
if (!isApi) {
const isAppTemplate = template.startsWith("app");
// Change the `Get started by editing pages/index` / `app/page` to include `src`
const indexPageFile = path.join(
"src",
isAppTemplate ? "app" : "pages",
`${isAppTemplate ? "page" : "index"}.${mode === "ts" ? "tsx" : "js"}`,
);
await fs.writeFile(
indexPageFile,
(await fs.readFile(indexPageFile, "utf8")).replace(
isAppTemplate ? "app/page" : "pages/index",
isAppTemplate ? "src/app/page" : "src/pages/index",
),
);
if (tailwind) {
const tailwindConfigFile = path.join(
root,
mode === "ts" ? "tailwind.config.ts" : "tailwind.config.mjs",
// Change the `Get started by editing pages/index` / `app/page` to include `src`
const indexPageFile = path.join(
"src",
isAppTemplate ? "app" : "pages",
`${isAppTemplate ? "page" : "index"}.${mode === "ts" ? "tsx" : "js"}`,
);
await fs.writeFile(
tailwindConfigFile,
(await fs.readFile(tailwindConfigFile, "utf8")).replace(
/\.\/(\w+)\/\*\*\/\*\.\{js,ts,jsx,tsx,mdx\}/g,
"./src/$1/**/*.{js,ts,jsx,tsx,mdx}",
indexPageFile,
(await fs.readFile(indexPageFile, "utf8")).replace(
isAppTemplate ? "app/page" : "pages/index",
isAppTemplate ? "src/app/page" : "src/pages/index",
),
);
if (tailwind) {
const tailwindConfigFile = path.join(
root,
mode === "ts" ? "tailwind.config.ts" : "tailwind.config.mjs",
);
await fs.writeFile(
tailwindConfigFile,
(await fs.readFile(tailwindConfigFile, "utf8")).replace(
/\.\/(\w+)\/\*\*\/\*\.\{js,ts,jsx,tsx,mdx\}/g,
"./src/$1/**/*.{js,ts,jsx,tsx,mdx}",
),
);
}
}
}
......@@ -236,6 +239,20 @@ export const installTemplate = async ({
};
}
if (isApi) {
delete packageJson.dependencies.react;
delete packageJson.dependencies["react-dom"];
// We cannot delete `@types/react` now since it is used in
// route type definitions e.g. `.next/types/app/page.ts`.
// TODO(jiwon): Implement this when we added logic to
// auto-install `react` and `react-dom` if page.tsx was used.
// We can achieve this during verify-typescript stage and see
// if a type error was thrown at `distDir/types/app/page.ts`.
delete packageJson.devDependencies["@types/react-dom"];
delete packageJson.scripts.lint;
}
const devDeps = Object.keys(packageJson.devDependencies).length;
if (!devDeps) delete packageJson.devDependencies;
......
......@@ -2,6 +2,7 @@ import { PackageManager } from "../helpers/get-pkg-manager";
export type TemplateType =
| "app"
| "app-api"
| "app-empty"
| "app-tw"
| "app-tw-empty"
......
......@@ -172,6 +172,23 @@ export const projectSpecification: ProjectSpecification = {
],
},
},
'app-api': {
js: {
deps: ['next'],
devDeps: [],
files: ['app/route.js', 'app/[slug]/route.js', 'jsconfig.json'],
},
ts: {
deps: ['next'],
devDeps: ['@types/node', '@types/react', 'typescript'],
files: [
'app/route.ts',
'app/[slug]/route.ts',
'tsconfig.json',
'next-env.d.ts',
],
},
},
'app-empty': {
js: {
deps: [],
......
import { join } from 'node:path'
import {
projectShouldHaveNoGitChanges,
tryNextDev,
run,
useTempDir,
projectFilesShouldExist,
} from '../utils'
import { mapSrcFiles, projectSpecification } from '../lib/specification'
import { projectDepsShouldBe } from '../lib/utils'
function shouldBeApiTemplateProject({
cwd,
projectName,
mode,
srcDir,
}: {
cwd: string
projectName: string
mode: 'js' | 'ts'
srcDir?: boolean
}) {
const template = 'app-api'
projectFilesShouldExist({
cwd,
projectName,
files: mapSrcFiles(projectSpecification[template][mode].files, srcDir),
})
projectDepsShouldBe({
type: 'dependencies',
cwd,
projectName,
deps: mapSrcFiles(projectSpecification[template][mode].deps, srcDir),
})
projectDepsShouldBe({
type: 'devDependencies',
cwd,
projectName,
deps: mapSrcFiles(projectSpecification[template][mode].devDeps, srcDir),
})
}
describe('create-next-app --api (Headless App)', () => {
let nextTgzFilename: string
beforeAll(() => {
if (!process.env.NEXT_TEST_PKG_PATHS) {
throw new Error('This test needs to be run with `node run-tests.js`.')
}
const pkgPaths = new Map<string, string>(
JSON.parse(process.env.NEXT_TEST_PKG_PATHS)
)
nextTgzFilename = pkgPaths.get('next')!
})
it('should create JavaScript project with --js flag', async () => {
await useTempDir(async (cwd) => {
const projectName = 'app-js'
const { exitCode } = await run(
[
projectName,
'--js',
'--api',
'--no-turbopack',
'--no-src-dir',
'--no-import-alias',
],
nextTgzFilename,
{
cwd,
}
)
expect(exitCode).toBe(0)
shouldBeApiTemplateProject({
cwd,
projectName,
mode: 'js',
})
await tryNextDev({
cwd,
isApi: true,
projectName,
})
})
})
it('should create TypeScript project with --ts flag', async () => {
await useTempDir(async (cwd) => {
const projectName = 'app-ts'
const { exitCode } = await run(
[
projectName,
'--ts',
'--api',
'--no-turbopack',
'--no-src-dir',
'--no-import-alias',
],
nextTgzFilename,
{
cwd,
}
)
expect(exitCode).toBe(0)
shouldBeApiTemplateProject({
cwd,
projectName,
mode: 'ts',
})
await tryNextDev({ cwd, isApi: true, projectName })
projectShouldHaveNoGitChanges({ cwd, projectName })
})
})
it('should create project inside "src" directory with --src-dir flag', async () => {
await useTempDir(async (cwd) => {
const projectName = 'app-src-dir'
const { exitCode } = await run(
[
projectName,
'--ts',
'--api',
'--no-turbopack',
'--src-dir',
'--no-import-alias',
],
nextTgzFilename,
{
cwd,
stdio: 'inherit',
}
)
expect(exitCode).toBe(0)
shouldBeApiTemplateProject({
cwd,
projectName,
mode: 'ts',
srcDir: true,
})
await tryNextDev({
cwd,
isApi: true,
projectName,
})
})
})
it('should enable turbopack dev with --turbopack flag', async () => {
await useTempDir(async (cwd) => {
const projectName = 'app-turbo'
const { exitCode } = await run(
[
projectName,
'--ts',
'--api',
'--turbopack',
'--no-src-dir',
'--no-import-alias',
],
nextTgzFilename,
{
cwd,
}
)
expect(exitCode).toBe(0)
const projectRoot = join(cwd, projectName)
const pkgJson = require(join(projectRoot, 'package.json'))
expect(pkgJson.scripts.dev).toBe('next dev --turbopack')
await tryNextDev({
cwd,
isApi: true,
projectName,
})
})
})
})
......@@ -46,11 +46,13 @@ export async function tryNextDev({
cwd,
projectName,
isApp = true,
isApi = false,
isEmpty = false,
}: {
cwd: string
projectName: string
isApp?: boolean
isApi?: boolean
isEmpty?: boolean
}) {
const dir = join(cwd, projectName)
......@@ -61,7 +63,7 @@ export async function tryNextDev({
try {
const res = await fetchViaHTTP(port, '/')
if (isEmpty) {
if (isEmpty || isApi) {
expect(await res.text()).toContain('Hello world!')
} else {
expect(await res.text()).toContain('Get started by editing')
......
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