Use next.js to develop URL shortening service

Posted Jun 16, 20202 min read

1. Principle of URL shortening service

The URL shortening service is not a compression algorithm. Instead, store the original URL in the database, use short parameters as the key, then take out the original URL and jump.

Therefore, short URLs are most suitable for key/value databases.

So, how to generate the unique parameters of the short URL? It is practical to convert from decimal to 62.

function string10to62(number) {
    var chars = '0123456789abcdefghigklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ'.split(''),
      radix = chars.length,
      qutient = +number,
      arr = [];
    do {
      let mod = qutient%radix;
      qutient =(qutient-mod)/radix;
    } while(qutient);
    return arr.join('');

Correspondingly, after each generation, a decimal number must be incremented, so that each time a unique 62 number can be generated based on the unique decimal number.

Why convert from decimal to 62?

Because, the 100000000 in the decimal system is converted to the 62 system, which is 6LAze. It's very short.

Second, how to get the parameters of the dynamic routing of next.js

Create file:pages/[slug].js

Note that the file name is composed of parentheses and represents a variable. In this way, the parameter xxx can be obtained in the form of http://ip/xxx .

Key code:

import {useRouter} from'next/router';
const router = useRouter();
const {slug} = router.query;

After getting the slug, go to the database to find and jump:

db.findOne({ slug:slug }, function(err, doc) {

3. github and demo

  1. github address:

  2. Demo address: