Welcome to the Treehouse Community
Looking to learn something new?
Javier Alvarado16,060 Points
Is it a convention to place routes in an index.js file?
In the Express Basics course, all of the routes were handled in the app.js file, but here the routes are placed into an index.js file. Is that the convention? Should we avoid putting routes in the app.js file?
Tom Geraghty24,162 Points
It's generally best to have your routes be in their own, separate file and then import them into the Express server file. This is modular code which is easier to read and understand rather than having a huge and confusing server file you can separate out the different functions into their own folders and files. That way if you need to make a change you can more quickly determine where that change should go based on the file structure.
For Node projects like this, if we are importing/loading resources from a directory, it is convention for the default file that the program looks for to load in a directory will be called index (similar to how navigating to a web address the default resource it looks for is a file called index.html --see this Treehouse answer: https://teamtreehouse.com/community/why-is-it-important-that-we-name-the-main-file-indexhtml)
Our routes directory in the previous Express course had a routes/index.js file (for the main routes) and a routes/cards.js file for the flashcards-specific routes. Both of these were then imported into our Express server.js file so they could be used the app.
Naming conventions change; but typically it's a good idea for clarity's sake to name your express server something obvious and descriptive like server.js, to put your routes in the routes folder, and to name your application (the logic the end user sees, not typically a server but the content and interaction that is delivered to the client) is called App.js.
But again, you can name anything as anything you want. These conventions are just to make it easier to jump into existing projects and make a more easily understood codebase.