Styling html pages in Node.js

Node.jsServer Side ProgrammingProgramming

In html files we can simply add style in head section −

         //add css code

We can add inline css styles as well in html directly.

Generally css is separated from the html code. Third option add css is to include a css file .

How to serve static files in Node.js?

Generally css files are added with below tag −

   <link rel=”stylesheet” href=”path-to-css-file”>

Express js provides a middleware to seve static file. This middleware gives read access to given folder.

app.use(express.static(path.join(__dirname, ‘public’)));

path: its our core module in node.js

__dirname: Actual path to root folder of project

Public: Folder name which has read access fom node server

Css files will be stored in public folder.

Example usage of css file −


const http = require('http');
const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const route = require('./routes');
const app = express();
app.use(bodyParser.urlencoded({extended: false})); app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res,next)=>{
   res.status(404).send('<h1> Page not found </h1>');
const server = http.createServer(app);

create a public folder in main project folder and store a main.css file under css folder in it.


input {


const path = require('path');
const express = require('express');
const router = express.Router();
router.get('/add-username', (req, res,next)=>{
   // res.send('<form action="/test/post-username" method="POST"> <input type="text" name="username">    <button type="submit"> Send </button> </form>');
   res.sendFile(path.join(__dirname, 'views', 'add-user.html'));
});'/post-username', (req, res, next)=>{
   console.log('data: ', req.body.username);
module.exports = router;


<!DOCTYPE html>
<html lang="en">
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <link rel="stylesheet" href="/css/main.css">
   <form action="/test/post-username" method="POST"> <input type="text" name="username"> <button          type="submit"> Send </button> </form>

Run : npm start

Browse: localhost:3000/test/add-username and we will updated css for input field from css file.

Published on 13-May-2020 17:06:53