Tutorials
API Routes
At the end of this tutorial, you’ll be able to create new API Routes for your application.
Any file named route.ts
in the
Here’s an example of an API Route that perform a Hello World:
export async function GET() {
return NextResponse.json({
message: 'Hello World'
})
}
Protected API Route
To create a protected api route, you need to decorate the example above with the withSession
helper:
export const GET = withSession(async ({ session }) => {
return NextResponse.json({
message: `Hello World from ${session.user.name}`
})
})
Project-based Protected API Route
To create an api route that refers to a given project and not the authenticated user, use the withAuth
helper:
export const GET = withAuth(async ({ project, req, session }) => {
return NextResponse.json({
message: `
Hello World from ${session.user.name},
member of ${project.name} project
`
})
})
Role Protection
withAuth
accepts a second optional argument with the following structure:
{
requiredRole: ['owner']
}
We can add it to an api route to make it available only to the owner of the project:
export const GET = withAuth(async ({ project, req, session }) => {
return NextResponse.json({
message: `
Hello World from ${session.user.name},
member of ${project.name} project
`
})
}, { requiredRole: ['owner'] })