DEV Community

shruti jain
shruti jain

Posted on

Serving a Widget Using Node.js šŸš€

Widgetsā€”those little UI elements like chat popups and notificationsā€”are super handy. Hereā€™s a quick way to build and serve a widget using Node.js, making it embeddable with a simple <script> tag.

1ļøāƒ£ Set Up the Server

mkdir widget-server && cd widget-server  
npm init -y  
npm install express  
Enter fullscreen mode Exit fullscreen mode

Create server.js:

const express = require('express');
const path = require('path');
const app = express();
const PORT = 3000;

app.get('/widget', (req, res) => res.sendFile(path.join(__dirname, 'widget.html')));

app.get('/embed.js', (req, res) => {
    res.setHeader('Content-Type', 'application/javascript');
    res.send(`
        (function() {
            let iframe = document.createElement('iframe');
            iframe.src = 'http://localhost:${PORT}/widget';
            iframe.style = 'width:320px;height:200px;border:none;position:fixed;bottom:20px;right:20px;z-index:9999;';
            document.body.appendChild(iframe);
        })();
    `);
});

app.listen(PORT, () => console.log(`Server running at http://localhost:${PORT}`));
Enter fullscreen mode Exit fullscreen mode

2ļøāƒ£ Create the Widget

Create widget.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Widget</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; padding: 10px; }
        button { background: #007BFF; color: #fff; padding: 10px; border: none; cursor: pointer; }
    </style>
</head>
<body>
    <h3>My Widget</h3>
    <button>Click Me</button>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

3ļøāƒ£ Embed It Anywhere

<script src="http://localhost:3000/embed.js"></script>
Enter fullscreen mode Exit fullscreen mode

Run the server:

node server.js  
Enter fullscreen mode Exit fullscreen mode

This will load the widget inside an iframe on any webpage. šŸš€****

Top comments (0)