Deploying a static HTML page and a serverless function (Node.js) live via Vercel

Vercel Node.js

In this example you will create a static HTML page that calls an api (Node.js serverless function) which responds by returning the word "Hello World" and displaying it in the browser. You can see a deployed version at: https://test-pi-tawny.vercel.app/

We will deploy and host both the HTML page and the Node.js api on Vercel using Vercel's cli, so you should register for a free account at vercel.com if you don't already have one and install vercel's command line via:


    npm install -g pnpm
    pnpm i -g vercel
    

  1. Run the following in terminal to create file and folder structure for "test" project:
    
        mkdir test
        cd test
        mkdir public api
        cd api
        touch index.js
        cd ../public
        touch index.html
        cd ..
        
  2. Open index.html in your editor and paste the following snippet there:
    
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <meta charset="utf-8" />
                <title>Hello World</title>
                <meta name="viewport" content="width=device-width, initial-scale=1" />
            </head>
            <body>
                <p id="test"></p>
                <script>
                  fetch('api/index.js')
                  .then((response) => response.text())
                  .then((text) => {
                    console.log(text);
                    document.getElementById('test').innerHTML = text;
                  });
                </script>
            </body>
        </html>
        
  3. Open index.js in your editor and paste the following snippet there:
    
        export default function handler(req, res) {
            res.setHeader('Content-Type', 'text/plain')
            res.write('Hello World')
            res.end()
        }
        
  4. In cli/terminal run:
    vercel dev
    and select default answers to all questions. Vercel cli will create the test project under your existing Vercel account and start a local server at: http://localhost:3000/ where you can see your index.html and your api can be reached at: http://localhost:3000/api/. If everything is working properly, you should see a "Hello World" message in your browser.
  5. To deploy your project to server for preview purposes run in terminal:
    vercel deploy
    And if you are happy with result and want to deploy it to production run:
    vercel --prod
    The preview and production URLs are available in your project on vercel.com under "Deployment" tab.

Back to Blog