Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Next JS - API utility folder structure

Tags:

api

next.js

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?

like image 540
Kabu Avatar asked Oct 12 '20 22:10

Kabu


People also ask

Does Next JS have a src folder?

The src directory is very common in many apps and Next. js supports it by default.

What is .next folder in next JS?

next build is the command which build the projects, which gives you . next folder containing all built content, which actually needs to be deployed on the server, but you will deploy the entire project folder, because you also need to install node modules.

Is next JS scalable?

Next. js is a scalable and high-performance React. js framework for modern web development and provides a large set of features, such as hybrid rendering, route prefetching, automatic image optimization, and internationalization, out of the box.


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

like image 116
Kelvin Sánchez Avatar answered Nov 15 '22 08:11

Kelvin Sánchez