Big News: Socket raises $60M Series C at a $1B valuation to secure software supply chains for AI-driven development.Announcement
Sign In

sql-escaper

Package Overview
Dependencies
Maintainers
1
Versions
11
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

sql-escaper

🛡️ Faster SQL escape and format for JavaScript (Node.js, Bun, and Deno).

Source
npmnpm
Version
1.0.0
Version published
Weekly downloads
1.8M
-40.72%
Maintainers
1
Weekly downloads
 
Created
Source

SQL Escaper

NPM Version Coverage
GitHub Workflow Status (Node.js) GitHub Workflow Status (Bun) GitHub Workflow Status (Deno)

🛡️ Up to 2x faster SQL escape and format for JavaScript (Node.js, Bun, and Deno).

Install

# Node.js
npm i sql-escaper
# Bun
bun add sql-escaper
# Deno
deno add npm:sql-escaper

[!NOTE]

🔐 SQL Escaper fixes a SQL Injection vulnerability discovered in 2022 in the original sqlstring, where objects passed as values could be expanded into SQL fragments, potentially allowing attackers to manipulate query structure. See sidorares/node-mysql2#4051 for details.

Usage

💡 SQL Escaper has the same API as the original sqlstring, so it can be used as a drop-in replacement.

Quickstart

import { escape, escapeId, format, raw } from 'sql-escaper';

escape("Hello 'World'");
// => "'Hello \\'World\\''"

escapeId('table.column');
// => '`table`.`column`'

format('SELECT * FROM ?? WHERE id = ?', ['users', 42]);
// => 'SELECT * FROM `users` WHERE id = 42'

format('INSERT INTO users SET ?', [{ name: 'foo', email: 'bar@test.com' }]);
// => "INSERT INTO users SET `name` = 'foo', `email` = 'bar@test.com'"

escape(raw('NOW()'));
// => 'NOW()'

For up-to-date documentation, always follow the README.md in the GitHub repository.

Import

ES Modules

import { escape, escapeId, format, raw } from 'sql-escaper';

CommonJS

const { escape, escapeId, format, raw } = require('sql-escaper');

API

escape

Escapes a value for safe use in SQL queries.

escape(value: SqlValue, stringifyObjects?: boolean, timezone?: Timezone): string
escape(undefined); // 'NULL'
escape(null); // 'NULL'
escape(true); // 'true'
escape(false); // 'false'
escape(5); // '5'
escape("Hello 'World"); // "'Hello \\'World'"

Dates

Dates are converted to YYYY-MM-DD HH:mm:ss.sss format:

escape(new Date(2012, 4, 7, 11, 42, 3, 2));
// => "'2012-05-07 11:42:03.002'"

Invalid dates return NULL:

escape(new Date(NaN)); // 'NULL'

You can specify a timezone:

const date = new Date(Date.UTC(2012, 4, 7, 11, 42, 3, 2));

escape(date, false, 'Z'); // "'2012-05-07 11:42:03.002'"
escape(date, false, '+01'); // "'2012-05-07 12:42:03.002'"
escape(date, false, '-05:00'); // "'2012-05-07 06:42:03.002'"

Buffers

Buffers are converted to hex strings:

escape(Buffer.from([0, 1, 254, 255]));
// => "X'0001feff'"

Objects

Objects with a toSqlString method will have that method called:

escape({ toSqlString: () => 'NOW()' });
// => 'NOW()'

Plain objects are converted to key = value pairs:

escape({ a: 'b', c: 'd' });
// => "`a` = 'b', `c` = 'd'"

Function properties in objects are ignored:

escape({ a: 'b', c: () => {} });
// => "`a` = 'b'"

When stringifyObjects is set to a non-nullish value, objects are stringified instead of being expanded into key-value pairs:

escape({ a: 'b' }, true);
// => "'[object Object]'"

Arrays

Arrays are turned into comma-separated lists:

escape([1, 2, 'c']);
// => "1, 2, 'c'"

Nested arrays are turned into grouped lists (useful for bulk inserts):

escape([
  [1, 2, 3],
  [4, 5, 6],
]);
// => '(1, 2, 3), (4, 5, 6)'

escapeId

Escapes an identifier (database, table, or column name).

escapeId(value: SqlValue, forbidQualified?: boolean): string
escapeId('id');
// => '`id`'

escapeId('table.column');
// => '`table`.`column`'

escapeId('i`d');
// => '`i``d`'

Qualified identifiers (with .) can be forbidden:

escapeId('id1.id2', true);
// => '`id1.id2`'

Arrays are turned into comma-separated identifier lists:

escapeId(['a', 'b', 't.c']);
// => '`a`, `b`, `t`.`c`'

format

Formats a SQL query by replacing ? placeholders with escaped values and ?? with escaped identifiers.

format(sql: string, values?: SqlValue | SqlValue[], stringifyObjects?: boolean, timezone?: Timezone): string
format('SELECT * FROM ?? WHERE id = ?', ['users', 42]);
// => 'SELECT * FROM `users` WHERE id = 42'

format('? and ?', ['a', 'b']);
// => "'a' and 'b'"

Triple (or more) question marks are ignored:

format('? or ??? and ?', ['foo', 'bar', 'fizz', 'buzz']);
// => "'foo' or ??? and 'bar'"

If no values are provided, the SQL is returned unchanged:

format('SELECT ??');
// => 'SELECT ??'

Objects in SET clauses

When stringifyObjects is falsy, objects used in SET or ON DUPLICATE KEY UPDATE contexts are automatically expanded into key = value pairs:

format('UPDATE users SET ?', [{ name: 'foo', email: 'bar@test.com' }]);
// => "UPDATE users SET `name` = 'foo', `email` = 'bar@test.com'"

format(
  'INSERT INTO users (name, email) VALUES (?, ?) ON DUPLICATE KEY UPDATE ?',
  ['foo', 'bar@test.com', { name: 'foo', email: 'bar@test.com' }]
);
// => "INSERT INTO users (name, email) VALUES ('foo', 'bar@test.com') ON DUPLICATE KEY UPDATE `name` = 'foo', `email` = 'bar@test.com'"

When stringifyObjects is truthy, objects are always stringified:

format('UPDATE users SET ?', [{ name: 'foo' }], true);
// => "UPDATE users SET '[object Object]'"

[!IMPORTANT]

Regardless of the stringifyObjects value, objects used outside of SET or ON DUPLICATE KEY UPDATE contexts are always stringified as '[object Object]'. This is a security measure to prevent SQL Injection.

raw

Creates a raw SQL value that will not be escaped.

raw(sql: string): Raw
escape(raw('NOW()'));
// => 'NOW()'

escape({ id: raw('LAST_INSERT_ID()') });
// => '`id` = LAST_INSERT_ID()'

Only accepts strings:

raw(42); // throws TypeError

TypeScript

You can import the available types:

import type { Raw, SqlValue, Timezone } from 'sql-escaper';

Performance

Each benchmark formats 10,000 queries using format with 100 mixed values (numbers, strings, null, and dates), comparing SQL Escaper against the original sqlstring through hyperfine:

BenchmarksqlstringSQL EscaperDifference
Select 100 values460.9 ms242.2 ms1.90x faster
Insert 100 values468.6 ms242.5 ms1.93x faster
SET with 100 values484.2 ms257.0 ms1.88x faster
SET with 100 objects671.6 ms283.2 ms2.37x faster
ON DUPLICATE KEY UPDATE with 100 values894.0 ms459.8 ms1.94x faster
ON DUPLICATE KEY UPDATE with 100 objects1,092.0 ms485.7 ms2.25x faster
  • See detailed results and how the benchmarks are run in the benchmark directory.

[!NOTE]

Benchmarks ran on GitHub Actions (ubuntu-latest) using Node.js LTS. Results may vary depending on runner hardware and runtime version.

Differences from sqlstring

  • Requires Node.js 12+ (the original sqlstring supports Node.js 0.6+)
  • TypeScript by default
  • Ships both CJS and ESM exports

[!TIP]

The Node.js 12+ requirement is what allows SQL Escaper to leverage modern engine optimizations and achieve the performance gains over the original.

Caution

Based on the original sqlstring documentation.

  • The escaping methods in this library only work when the NO_BACKSLASH_ESCAPES SQL mode is disabled (which is the default state for MySQL servers).

  • This library performs client-side escaping to generate SQL strings. The syntax for format may look similar to a prepared statement, but it is not — the escaping rules from this module are used to produce the resulting SQL string.

  • When using format, all ? placeholders are replaced, including those contained in comments and strings.

  • When structured user input is provided as the value to escape, care should be taken to validate the shape of the input, as the resulting escaped string may contain more than a single value.

  • NaN and Infinity are left as-is. MySQL does not support these values, and trying to insert them will trigger MySQL errors.

  • The string provided to raw() will skip all escaping, so be careful when passing in unvalidated input.

Security Policy

GitHub Workflow Status (with event)

Please check the SECURITY.md.

Contributing

See the Contributing Guide and please follow our Code of Conduct 🚀

Acknowledgements

  • Contributors
  • SQL Escaper is adapted from sqlstring (MIT), modernizing it with high performance, TypeScript support and multi-runtime compatibility.
  • Special thanks to Douglas Wilson for the original sqlstring project and its contributors.

License

SQL Escaper is under the MIT License.
Copyright © 2026-present Weslley Araújo and SQL Escaper contributors.

Keywords

sql

FAQs

Package last updated on 04 Feb 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts