Separating styles for front and back ends in Express.js app

Hey everyone, I’m building a web app using Express.js and I’m stuck. I’ve set up separate folders for my frontend and backend, but I’m having trouble with the stylesheets.

My folder structure looks like this:

myapp/
  ├── client/
  │     ├── assets
  │     └── views
  ├── admin/
  │     ├── assets
  │     └── views
  └── app.js

In app.js, I’ve got:

const express = require('express');
const app = express();

const adminRoutes = require('./admin/routes');
const clientRoutes = require('./client/routes');

app.use(adminRoutes);
app.use(clientRoutes);

app.listen(3000);

The problem is, no matter which page I visit, it’s always loading the admin stylesheet. How do I make it use the right CSS for each part of the site? Any help would be awesome!

To address your stylesheet issue, you might want to consider implementing view engines and separate layouts for your admin and client sections. This approach allows you to specify different stylesheets for each part of your application.

In your app.js, you could set up two different view engines:

app.set('views', ['./admin/views', './client/views']);
app.set('view engine', 'ejs');  // or whichever engine you prefer

Then, create separate layout files for admin and client, each referencing its own stylesheet. In your route handlers, use res.render() with the appropriate layout:

res.render('adminPage', { layout: 'admin' });
res.render('clientPage', { layout: 'client' });

This method ensures that the correct stylesheets are loaded for each section of your application, maintaining a clear separation between admin and client styles.

hey jasper, i ran into similar issue before. try using separate static middleware for each route:

app.use(‘/admin’, express.static(‘admin/assets’));
app.use(‘/’, express.static(‘client/assets’));

this way, admin styles load only for admin routes and client styles for client routes. hope this helps!

hey there! have u considered using a template engine like handlebars or ejs? it could help manage different layouts for admin and client. you could set up separate layout files with their own stylesheets. curious, what made you choose express for this project? any specific features you’re looking to implement?