Search code examples
mongoosenext.jsserverbackendaction

Nextjs actions, how to make a mongoose call from action?


and should it be done? or should the actual mongoose call of find needs to be inside route.ts file as an api and inside the action of nextjs i should make a http fetch call to this api?

my problem is mostly:

  • should i make the mongoose find command inside (server side) action
  • if so, how to convert to json, as in regular code we'd be using nextResponse.json to conv the mongoose to a json

Thanks


Solution

  • The purpose of actions in nextjs are to seperate concerns between the view to the data manipulation like http fetch from the server side of nextjs - meaning that when a component that initially rendered in the backend can perform a server side http request and afterwards perform the same http request on the client side with the same actions - this is why it's important to have a separation of concerns to allow the isomoprhic nature of the code execute smoothly!

    Here are some best practice for action in nextjs:

    • action should not contain JSX/HTML or anything related to view layer representation
    • action should not contain direct calls to DB
    • logic should be avoided and in some cases non exists in action (because the more logic you add the less reusable actions are).

    The goal of actions in nextjs are:

    • be reusable
    • separate concerns (between view, controller to model - the classic MVC)
    • easy to test

    Good luck!