I'm using Next JS and the api routes to create my apis. I have 2 questions if anyone can answer.
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?
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?
The src directory is very common in many apps and Next. js supports it by default.
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.
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.
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
import dbConnect from '../../utils/dbConnect';
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With