Skip to content
Sign upLog in
← Back to Community

How do you put CSS in Node.js?

Profile icon
DTSMicahHacker

I was trying to learn Node.js. However, I cannot get any CSS to work in separate HTML files, with , and can't get JavaScript in it either. Any help, please?

Voters
Profile icon
DTSMicah
Comments
hotnewtop
Profile icon
SixBeeps

Take a peek at line 7, app.use(express.static('public'));

This line marks a folder named public as a static folder. You can only GET something from a server if there's a routing for it (like using app.get in your server code) or if it's marked as static. So, if you want to GET some content, in your case some CSS and JS files, you'll have to make a new folder with those files in it and mark that folder as static.

Since you've already marked public as static, I'd recommend just naming the folder that. Then, put your CSS and JS files in there, then changing the URLs for those accordingly (i.e. add public/ to each).

Profile icon
DTSMicah

@SixBeeps
Ok I tried that but it didn't work. Can you fork the project and show me what I'm doing wrong? Thanks!

Profile icon
SixBeeps

@DTSMicah
Oh wait sorry I forgot one more thing.

You need to actually route an endpoint to the folder, so the full line should be app.use('/public', express.static(__dirname + '/public'));

Profile icon
DTSMicah

@SixBeeps
u mean app.use(express.static('public'), express.static(__dirname + '/public'), right?

Profile icon
DTSMicah

@SixBeeps
and replace line 7 with that?

Profile icon
SixBeeps

@DTSMicah
No, I meant what I said. And yes, that's your new line 7.

Profile icon
SixBeeps

@DTSMicah
Like this is a line from my Node template that I use: app.use('/static', express.static(__dirname + '/static'));. I just changed mine to fit yours.

Profile icon
ReplitCoder100

@SixBeeps
So does that line work?

Profile icon
SixBeeps

@ReplitCoder100
It should.

Also since this is the second time you've left a comment on one of my Repl Talk answers (Repl Talk is deprecated) I'd suggest you join the Discord if you can.

Profile icon
DTSMicah

@SixBeeps
I am in the discord, at least now.