Nextjs change /pages/api to /pages/myApi?

Viewed 4840
1 Answers

I believe you can't change /api path because Next.js looks specifically in that location

// Regex for API routes
export const API_ROUTE = /^\/api(?:\/|$)/

If you want to make /api directory work as any other directory in /pages you can use rewrite option.

next.config.js

module.exports = {
    rewrites: [
        { source: '/api/:path*', destination: '/another-directory/:path*' }
    ],
};

In that case requesting /api would serve content of /another-directory.

However, you can write a custom server for API routes. Note, that you might need to disable or overwrite default file system routing.

Suggested reading:

Related