Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add headless api template #68138

Open
wants to merge 3 commits into
base: canary
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion packages/create-next-app/create-app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ export async function createApp({
skipInstall,
empty,
turbo,
api,
}: {
appPath: string
packageManager: PackageManager
Expand All @@ -51,10 +52,13 @@ export async function createApp({
skipInstall: boolean
empty: boolean
turbo: boolean
api: boolean
}): Promise<void> {
let repoInfo: RepoInfo | undefined
const mode: TemplateMode = typescript ? 'ts' : 'js'
const template: TemplateType = `${appRouter ? 'app' : 'default'}${tailwind ? '-tw' : ''}${empty ? '-empty' : ''}`
const template: TemplateType = api
? 'headless-api'
: `${appRouter ? 'app' : 'default'}${tailwind ? '-tw' : ''}${empty ? '-empty' : ''}`

if (example) {
let repoUrl: URL | undefined
Expand Down Expand Up @@ -232,6 +236,7 @@ export async function createApp({
importAlias,
skipInstall,
turbo,
api,
})
}

Expand Down
25 changes: 22 additions & 3 deletions packages/create-next-app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,7 @@ const program = new Command(packageJson.name)
Initialize with Tailwind CSS config. (default)
`
)

.option(
'--eslint',
`
Expand Down Expand Up @@ -97,6 +98,13 @@ const program = new Command(packageJson.name)
`

Specify import alias to use (default "@/*").
`
)
.option(
'--api',
`

Initialize a Headless API App
`
)
.option(
Expand Down Expand Up @@ -345,7 +353,8 @@ async function run(): Promise<void> {

if (
!process.argv.includes('--tailwind') &&
!process.argv.includes('--no-tailwind')
!process.argv.includes('--no-tailwind') &&
!program.api
) {
if (ciInfo.isCI) {
program.tailwind = getPrefOrDefault('tailwind')
Expand Down Expand Up @@ -387,7 +396,11 @@ async function run(): Promise<void> {
}
}

if (!process.argv.includes('--app') && !process.argv.includes('--no-app')) {
if (
!process.argv.includes('--app') &&
!process.argv.includes('--no-app') &&
!program.api
) {
if (ciInfo.isCI) {
program.app = getPrefOrDefault('app')
} else {
Expand All @@ -405,7 +418,11 @@ async function run(): Promise<void> {
}
}

if (!program.turbo && !process.argv.includes('--no-turbo')) {
if (
!program.turbo &&
!process.argv.includes('--no-turbo') &&
!program.api
) {
if (ciInfo.isCI) {
program.turbo = getPrefOrDefault('turbo')
} else {
Expand Down Expand Up @@ -484,6 +501,7 @@ async function run(): Promise<void> {
skipInstall: program.skipInstall,
empty: program.empty,
turbo: program.turbo,
api: program.api,
})
} catch (reason) {
if (!(reason instanceof DownloadError)) {
Expand Down Expand Up @@ -515,6 +533,7 @@ async function run(): Promise<void> {
skipInstall: program.skipInstall,
empty: program.empty,
turbo: program.turbo,
api: program.api,
})
}
conf.set('preferences', preferences)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"extends": "next/core-web-vitals"
"extends": "next/typescript"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Rename this file to `.env.local` to use environment variables locally with `next dev`
# https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
MY_HOST="example.com"
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
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/api/posts/route.js`. 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.
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
// Helper function to validate post data
function validatePostData(data) {
return (
typeof data.title === "string" &&
typeof data.content === "string" &&
typeof data.authorId === "string"
);
}

// GET: Retrieve a post by ID
export async function GET(request, { params }) {
const postId = params.postId;

// In a real app, you'd fetch the post from a database
const post = {
id: postId,
title: "Sample Post",
content: "This is a sample post content.",
authorId: "author123",
createdAt: new Date().toISOString(),
};

return NextResponse.json(post);
}

// PUT: Update an existing post
export async function PUT(request, { params }) {
const postId = params.postId;
const data = await request.json();

if (!validatePostData(data)) {
return NextResponse.json({ error: "Invalid post data" }, { status: 400 });
}

// In a real app, you'd update the post in a database
const updatedPost = {
id: postId,
...data,
updatedAt: new Date().toISOString(),
};

return NextResponse.json(updatedPost);
}

// DELETE: Remove a post
export async function DELETE(request, { params }) {
const postId = params.postId;

// In a real app, you'd delete the post from a database
// Here, we'll just return a success message
return NextResponse.json({ message: `Post ${postId} deleted successfully` });
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Helper function to validate post data
function validatePostData(data) {
return (
typeof data.title === "string" &&
typeof data.content === "string" &&
typeof data.authorId === "string"
);
}

// GET: Retrieve all posts
export async function GET() {
const posts = [
{
id: "1",
title: "First Post",
content: "Content of the first post",
authorId: "author123",
createdAt: new Date().toISOString(),
},
{
id: "2",
title: "Second Post",
content: "Content of the second post",
authorId: "author456",
createdAt: new Date().toISOString(),
},
];

return NextResponse.json({
posts,
total: posts.length,
});
}

// POST: Create a new post
export async function POST(request) {
const data = await request.json();

if (!validatePostData(data)) {
return NextResponse.json({ error: "Invalid post data" }, { status: 400 });
}

const newPost = {
id: Date.now().toString(),
...data,
createdAt: new Date().toISOString(),
};

return NextResponse.json(newPost, { status: 201 });
}

// OPTIONS: Handle preflight requests
export async function OPTIONS(request) {
return new NextResponse(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization",
},
});
}
36 changes: 36 additions & 0 deletions packages/create-next-app/templates/headless-api/js/gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js
.yarn/install-state.gz

# 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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"compilerOptions": {
"paths": {
"@/*": ["./*"]
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
/** @type {import('next').NextConfig} */
const nextConfig = {};

export default nextConfig;
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Rename this file to `.env.local` to use environment variables locally with `next dev`
# https://nextjs.org/docs/app/building-your-application/configuring/environment-variables
MY_HOST="example.com"
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"extends": "next/core-web-vitals"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
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/api/posts/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.
Loading
Loading