Ask coding questions

← Back to all posts
How do you put CSS in Node.js?
DTSMicah

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

Voters
DTSMicah
Comments
hotnewtop
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).

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!

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

DTSMicah

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

DTSMicah

@SixBeeps and replace line 7 with that?

SixBeeps

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

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.