Next JS - API utility folder structure

Viewed 8683

I'm using Next JS and the api routes to create my apis. I have 2 questions if anyone can answer.

  1. If I want to use a utility function or global constant variables that I need to include in multiple api files where is the best place to store it in? And to import them using relative paths?

  2. Is there an example of a Next JS project that isn't just your basic api routes tutorial to learn from in terms of folder structures?

1 Answers

You can save your util functions on a utils folder on the root of your project folder.

|-root
  |-components
    |-Navbar.js
    |-Footer.js
  |-styles
    |-global.css 
    |-navbar.module.css   
    |-footer.module.css        
  |-pages
    |-api
      |-users.js
    |-index.js
  |-utils
    |- dbConnect.js

Lets say you want to import dbConnect.js from pages/api/user.js

  • Relative import:

import dbConnect from '../../utils/dbConnect';

  • Absolute import:

import dbConnect from 'src/utils/dbConnect';

Here is a link to an example project that may help you: https://github.com/vercel/next.js/tree/canary/examples/with-mongodb-mongoose

If you are interested in using Absolute Imports you can check this documentation link: https://nextjs.org/docs/advanced-features/module-path-aliases

Related