1

I have setup new next project and used the app router as next recommend this in latest version. Now I want to create the API so how can I create and use this API inside my page app/user/page.tsx?

I have create one API inside the app/api/user/page.tsx but it seems not working properly like actual it should work as API

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
  • Can you [edit] to clarify what exactly you mean by "create api with app router" and include a [mcve] of the relevant code you are working with? – Drew Reese Aug 25 '23 at 06:00
  • @DrewReese it is simple i have created a fresh next setup and there is 2 way to use page route using `app` and `page` So as per the next recommendation I have used the `app router` https://nextjs.org/docs/getting-started/installation#the-app-directory So now I just want to create one API inside the next so how can I do this do I need to create API inside `pages/api/user.tsx`? This is right way if not please explain this! – Kishan Bhensadadiya Aug 25 '23 at 06:07
  • Are you asking about how to create, or access, a ***backend*** API? API to *what*? This sort of [API](https://en.wikipedia.org/wiki/API)? I don't understand what you mean by "create API inside ....". – Drew Reese Aug 25 '23 at 06:10
  • Yes want to access backend as next is the full stake and we can create and use API inside the next it self so yes I want to access backend and start development and building rest API inside the next – Kishan Bhensadadiya Aug 25 '23 at 06:13
  • I see, then yes, we'll certainly need to see a [mcve] for what you are trying to do... unless you haven't actually done anything yet and you are just asking how, in which case might be considered too broad a question for StackOverflow and need to focused to a single specific topic/issue. – Drew Reese Aug 25 '23 at 06:18

1 Answers1

0

In Nextjs 13 the you can create an API with the route.ts file.

Instead of app/api/user/page.tsx create a app/api/user/route.ts.

Also there cannot be a route.ts file at the same route segment level as page.ts.

More information on Nextjs docs

Hope this helps :)

  • thank you for your answer! I have checked the doc as well can you please explain with an example as you mentioned line above please? Also there cannot be a route.ts file at the same route segment level as page.ts. – Kishan Bhensadadiya Aug 25 '23 at 06:30
  • > Also there cannot be a route.ts file at the same route segment level as page.ts This basically means that there cannot be a `route.ts` **and** `page.ts` file for the same route. – Dharmik_403 Aug 25 '23 at 06:53