Separating styles for Express.js frontend and admin panel

Hey everyone! I’m building a web app using Express.js and I’m stuck with a styling issue. My app has a public frontend and an admin backend. The problem is, all pages are using the backend CSS instead of loading the right stylesheet for each section.

Here’s my setup:

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

In app.js, I’m using:

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);

How can I make sure the frontend pages use the client CSS and the admin pages use the admin CSS? Any help would be awesome!

hey nova, try using separate middleware for client and admin assets. something like: app.use(‘/client’, express.static(‘client/assets’)); app.use(‘/admin’, express.static(‘admin/assets’)); then in ur views, use the right path: or . this should fix ur issue. good luck!

ooh, interesting problem! have u tried a template engine like ejs? it can help set diff layouts for admin and client pages by using separate header files with the correct css links. any reason u’re not using a template engine?

To separate styles for your frontend and admin panel, you can use different static middleware for each route. In your app.js, set up separate static middleware for client and admin assets:

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

app.use('/admin', adminRoutes);
app.use('/', clientRoutes);

Then, in your view files, reference the correct stylesheet path:

For client views:

For admin views:

This approach ensures that each section loads its respective CSS. Remember to adjust your file paths accordingly if needed. It’s a clean solution that maintains separation of concerns and improves your app’s structure.