jsdrop.

Link shortener starter

Short links with nanoid: POST a URL, get a short code that redirects.

Open in editor Free. Runs in your browser, no sign-up.
  • nanoid
Links

The code

Two files, exactly what you get in the editor.

import { createServer } from 'node:http'
import { nanoid } from 'nanoid'

const links = new Map<string, string>([['jsdrop', 'https://jsdrop.com']])

const server = createServer(async (req, res) => {
  const url = new URL(req.url ?? '/', 'http://localhost')

  if (req.method === 'POST' && url.pathname === '/shorten') {
    let body = ''
    for await (const chunk of req) body += chunk
    try {
      const target = new URL(JSON.parse(body).url).toString()
      const code = nanoid(7)
      links.set(code, target)
      res.writeHead(201, { 'content-type': 'application/json' })
      return res.end(JSON.stringify({ code, short: `/${code}`, target }))
    } catch {
      res.writeHead(400, { 'content-type': 'application/json' })
      return res.end(JSON.stringify({ error: 'Send JSON like {"url": "https://…"}' }))
    }
  }

  const target = links.get(url.pathname.slice(1))
  if (target) {
    res.writeHead(302, { location: target })
    return res.end()
  }
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' })
  res.end(`<h1>Link shortener</h1><p>${links.size} links. Try <a href="/jsdrop">/jsdrop</a>.</p>`)
})

const port = Number(process.env.PORT) || 3000
server.listen(port, () => console.log(`Shortener on port ${port}`))
{
  "name": "link-shortener",
  "private": true,
  "type": "module",
  "dependencies": {
    "nanoid": "^5.1.0"
  }
}

Questions

Can I run Link shortener in the browser?

Yes. Press Run and the program runs in a Node.js-compatible runtime, compiled to WebAssembly, right in your browser tab. npm packages install in the browser too.

How do I start a Link shortener project online?

Click Open in editor. jsdrop copies this starter into a new drop with index.ts and package.json. Press Run to start it, and edit as you go.

Can other people reach my server?

Yes. When the program calls listen(), the preview shows the server and a public tunnel URL that works while your tab runs it. With Pro, deploy the drop to run around the clock at its own address.

Is it free?

Yes. Public drops, running in the browser, live collaboration, versions, and embeds are free, and you do not need an account to start.

More starter kits