So Iβve successfully created my first express server with the help of this YouTube video and ChatGPT. Itβs all working good at the moment. Iβve decided to use MongoDB Atlas as my database and Iβm exited to see where it takes me.
This is the file structure for the express server:
π project-root-directory/
β
βββ π src/ # Source files
β βββ π config/ # Configuration files (e.g., database connection, middleware)
β βββ π controllers/ # Route controllers (controller logic for your routes)
β βββ π middleware/ # Express middlewares (e.g., logging, error handling)
β βββ π models/ # Mongoose database models and schemas
β βββ π services/ # Mongoose CRUD operations and business logic
β βββ π routes/ # Express route definitions
β βββ π utils/ # Utility/helper functions
β βββ index.ts # Main application entry
β
βββ π dist/ # Compiled JavaScript files (output from TypeScript compiler)
β
βββ π tests/ # Test files (e.g., unit, integration tests)
β
βββ π node_modules/ # Node.js dependencies
β
βββ .env # Environment variables
βββ .gitignore # Specifies intentionally untracked files to ignore
βββ package.json # Project metadata and dependencies
βββ nodemon.json # Nodemon config
βββ package-lock.json # Describes exact tree generated (if using npm)
βββ tsconfig.json # TypeScript configuration file
βββ README.md # Documentation for the project
Several years ago I did some .NET (C#) development for the first company that I worked for as a graduate software developer. This express.js server structure looks very similar to the .NET servers that I worked with. At the time the codebase was so big I couldnβt really see the full picture of how everything worked. However, now, after putting everything together from scratch it all makes sense.
Wow Clerk made this so damn easy. I didnβt realise how much went into authentication and authorisation. However, this time round I donβt want to depend on clerk. Itβs great. However, for B2C apps itβs just not worth it. Itβs too expensive for large scale apps with a freemium model or low price point.
Iβve finally got it all working (I think) using my own sessionTokens.
Essentially when a user signs in they get a sessionToken sent back as a cookie. This sessionToken is stored on the browser and anytime the user makes a request to the Server the sessionToken is sent to the Server as a cookie. The server then looks up the DB and makes sure that the sessionToken corresponds to a user, and checks if this user is authenticated / authorised to access certain pages.
I have also created a middleware.ts file that ensures that the user can only access public routes if unauthenticated. Otherwise they get redirected to the SignIn page.