TypeScript icon, indicating that this package has built-in type declarations

    1.0.2 • Public • Published


    This module provides a function for calculating text width in pixels. In the browser you have that capability out of the box (with canvas or with hidden element) but not in nodejs. It is useful for server side rendering when you need to trim text to some fixed size or to draw something around the text.


    npm install server-text-width


    yarn add server-text-width


    • no dependencies
    • works in node and in browser same way
    • supports unicode characters (not only latin or ASCII)
    • supports multiple fonts (your own fonts as well)
    • supports multiple font sizes
    • supports font weight
    • typescript definitions included
    • minimizes size of table data

    How it works?

    Original idea was borrowed from

    1. Open special tool mappingTool.html included in that package
    2. In that tool choose font name, size and weight. Also select range of unicode characters.
    3. The tool generates you table with widths for each character.
    4. Put a table into your source as constant and initialize module with it.
    5. Now you have function that can measure text width.

    Step by step

    Open mappingTool.html in you browser. You can download it from github


    Select font you want to measure, font size, font weight and range of characters. All unicode pages are already here. You can select based on locale (or locales) you use. You can also experiment with text using input on top. All characters that are not covered with selected unicode ranges will be highlighted with red.

    At the very bottom the tool will generate you table data, that you need to feed into module. Each character width is represented with 2 symbols in base 64 encoding. One for integer and one for fractional part (in font rendered characters have fractional width in pixels). That is much more compact than storing data in JSON.

    In your code create a constant variable with that value.


    NOTE: If you need multiple fonts, sizes, weight or ranges just merge that dictionary manually. The tool is limited to produce only one set at the time for simplicity.

    Then just import and initialize the module

    import { init } from 'server-text-width';
    const { getTextWidth } = init(TEXT_WIDTH_LOOKUP_TABLE);
    const width = getTextWidth('Measure my text');

    That is it. Enjoy your server side text rendering. Star my repo if you like it :)

    Future work

    PRs are very welcome

    • add text variants (italic)
    • add web fonts support to the tool




    npm i server-text-width

    DownloadsWeekly Downloads






    Unpacked Size

    42.4 kB

    Total Files


    Last publish


    • evgenus