Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript User Authentication With Express and Mongo What is Authentication? Setting Up the Project

Javier Alvarado
Javier Alvarado
16,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?

1 Answer

Tom Geraghty
Tom Geraghty
24,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.