Separating styles for Express.js frontend and admin panel

I’m building a web app using Express.js. It has a public-facing frontend and an admin backend. The frontend shows database content while the backend lets me add new stuff like a CMS.

My folder setup looks like this:

myapp/
  ├── client/
  │     ├── assets
  │     ├── templates
  │     └── main.js
  │
  ├── admin/
  │     ├── assets
  │     ├── templates
  │     └── dashboard.js
  │
  └── app.js

I’ve got the templates working, but the stylesheets are messed up. Every page loads the admin CSS, even on the frontend. For example, /about should use the CSS from client/assets/css/ while /admin should load admin/assets/css/.

How can I fix this so that each section of the site uses its own styles? Any tips on Express.js routing or static file serving would be appreciated. Thanks!

To solve your styling issue, you need to set up separate static file serving for your frontend and admin panel. In your Express app, use middleware to serve static files from different directories:

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

This ensures that frontend routes use client/assets for styles, while admin routes use admin/assets.

In your HTML templates, adjust the stylesheet links accordingly:

For frontend pages:
For admin pages:

This approach keeps your styles separate and loads the correct CSS for each section of your site. Remember to organize your routes clearly to avoid conflicts between frontend and admin paths.

hey max, try this:

in ur app.js, add:

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

then in ur html, use:

for frontend for admin

shud fix ur issue. lmk if u need more help!

hmmm, interesting setup! have u considered using a template engine like EJS? it could help u dynamically include the right stylesheet based on the route. something like:

<% if (isAdmin) { %>

<% } else { %> <% } %>

might be worth exploring. what do u think?