Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

next.js

Next has a built in API route https://nextjs.org/docs/api-routes/introduction

It uses /pages/api

Is it possible to change the default path from /api/* to something else like /myApi/*?

I was thinking about adding it to exportPathMap https://nextjs.org/docs/api-reference/next.config.js/exportPathMap

Any suggestions?

like image 630
Leon Avatar asked Mar 26 '20 18:03

Leon


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:

  • API directory is hardcoded
  • Custom server in Next.js
  • Disable file-system routing
  • Custom Routes
like image 52
Nikolai Kiselev Avatar answered Jan 01 '23 18:01

Nikolai Kiselev