Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJavier Alvarado
16,060 PointsIs 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?
1 Answer
Tom Geraghty
24,174 PointsIt'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.