The debate between using backticks and colons in TypeORM queries

Lately, I've been crafting queries utilizing backticks

const firstUser = await connection
    .getRepository(User)
    .createQueryBuilder("user")
    .where(`user.id = '${id}'`)
    .getOne();

However, in the typeorm documentation, examples are shown with colons.

const firstUser = await connection
    .getRepository(User)
    .createQueryBuilder("user")
    .where("user.id = :id", { id: 1 })
    .getOne();

This made me ponder about whether there is a distinction between using backticks and colons.

I would greatly appreciate any insights or advice.

Thank you.

Answer №1

A WARNING AGAINST USING STRING INTERPOLATION FOR SQL STATEMENTS

Apologies for the shouting, but this is crucial.


When you utilize this method:

.where(`user.id = '${id}'`)

The string is constructed beforehand and then passed to the where() function. So, if id equals 123, it's essentially the same as:

.where(`user.id = '123'`)

This might seem okay. However, what if id is 123' OR 1=1--'

You will end up with:

.where(`user.id = '123' OR 1=1--'`) // Now returns ALL users!

This dangerous practice is known as SQL injection, posing severe security risks. Attackers can manipulate your queries, gain unauthorized data access, alter records to grant themselves admin privileges, or execute various malicious activities. It's almost like granting everyone unrestricted database control.


Which brings us to the solution:

.where("user.id = :id", { id: 1 })

To safeguard against this threat, TypeORM handles value insertion for you, ensuring proper escaping of any potentially harmful inputs to prevent execution of unauthorized commands.

If id contains suspicious content, it will be transformed into something like:

.where(`user.id = '123\' OR 1=1--'`) // note the backslash
// (actual query may vary based on different databases)

This approach secures the processing of user-provided values by correctly escaping manipulated characters inserted by attackers. Thus, enabling safe inclusion of such values in your queries.


In summary, AVOID directly interpolating user inputs into queries (ideally all inputs), and instead, always rely on query parameters to ensure proper value handling and prevention of SQL injection vulnerabilities.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

retrieve a static method that returns an asynchronous value

Is there a way to have a static ES6 method in my code that simply returns a value instead of a promise? I'm looking for a solution to this problem: export default class Member { static existingMember() { var _existingMember; // DB.findExist ...

Showing off the latest products at the top of the list

Typically, when utilizing ngFor, the most recent item is displayed underneath the initial element. For instance, a list containing: [Apple, Orange, Banana] If we use ngFor to display this list: Apple Orange Banana I am interested in learning a method t ...

Guide to uploading files in Vue.js v3

I'm trying to implement file upload functionality using Vue.js version 3. Although I have successfully imported ref, I am unsure how to utilize it for retrieving file data? FileUploadTest.vue <template> <h1>File Upload</h1> <div ...

Eliminate the unnecessary code repetition in my functions using Typescript

I have 2 specific functions that manipulate arrays within an object. Instead of repeating the same code for each array, I am looking for a way to create reusable functions. Currently, my functions look like this: setLists(): void { if (this.product.ord ...

When working with VueJS and Vuex, using the splice method to replace an item (object) in an array stored in Vuex does not trigger a re-render of the

I have an array of records. Each record consists of an object with _id (mongo id), title, and value (value is an object with amount and currency). When displaying the list of records using v-for, the ':key' for each item in the list is set to th ...

What is the best way to prompt users to submit comments with a popup textarea box?

Within my project, I have incorporated a dropdown list: <div class="dropdown"> <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown">Select subject <span class="caret"></span> </but ...

Utilize Angular to initiate the transmission of attribute values upon a click event

My question may be simple, but I've been struggling to find an answer. How can I send attributes or item property bindings of an item through a click event in the best way? For example: <item class="item" [attr.data-itemid]="item.id ...

What might be preventing combineLatest from executing?

Currently, I am attempting to run a block of code utilizing the combineLatest function. Within my translation library, there exists an RXJS Observable that is returned. Imported as individual functions are combineLatest, map, and tap. combineLatest(this. ...

Managing post requests in node.js using busboy and then multer

I'm currently facing an issue with busboy (or multiparty) and multer while trying to parse my request. Initially, the request is received successfully using busboy, where I proceed to create a folder and update my database. However, when I attempt to ...

Guide on generating a dynamic loop in JavaScript using the group name as a variable

I have been attempting to organize a group, dynamically ungroup it, and then create a loop with each element of the group. Despite reviewing multiple examples, I have not been able to solve the following issue: The grouping is done based on the "tipo" pro ...

How to efficiently retrieve parent content from a child component

parent.html <ion-content class="project"> <ion-grid> <ion-row class="details"> <project [data]="data"></project>// this child component </ion-row> </ion-grid> </ion-content> project.ht ...

Is there a way to execute publish without automatically triggering postpublish?

I am working on a project that includes a specific postpublish action in its package.json. Recently, I encountered a situation where I need to run the publish command without triggering the associated postpublish action. Is there a foolproof method to exe ...

Shortening a jQuery If-Else Statement in JavaScript

I am working on a snippet of code and need some help. Here is the code: <script type="text/javascript"> $(window).load(function() { if(!$.browser.msie){ $('#myDiv').animate({opacity: 1}, 300); } else if ($.browser.msie) { ...

Improving Page Load Speed with HTML Caching: Strategies for Enhancing Performance when over half of the data transferred is for navigation menus

I manage a complex and expansive website that contains a significant amount of repetitive HTML elements such as the navigation menu and top ribbon. Loading a single page on my site can be resource-intensive, with up to 300KB of data required, half of whic ...

Chrome stack router outlet and the utilization of the Angular back button

I'm experiencing an issue with the back button on Chrome while using Angular 14. When I return to a previous page (URL), instead of deleting the current page components, it keeps adding more and more as I continue to press the back button (the deeper ...

Smart method for repositioning multiple elements on the display

Imagine we have multiple divs displayed on a screen: https://i.stack.imgur.com/jCtOj.png ...and our goal is to move them collectively, either to the left: https://i.stack.imgur.com/KBfXC.png ...or to the right: https://i.stack.imgur.com/c1cUw.png An ...

How is it that void can be assigned undefined?

According to the documentation on typescript, it states that "the one exception being that undefined is also assignable to void". Source Strict null checking mode specifies that null and undefined values are not within the domain of every type and can o ...

Echarts: scatter plots linked with a line to the axis (resembling the PACF diagram)

I am currently working with echarts (js). Is there a method to link the dot of the scatter plot with the 0 value on the y-axis? I want it to resemble a pacf plot, similar to this example: The desired outcome should look something like this: https://i.sta ...

How can I retrieve a PDF from a URL provided by the server using AngularJS?

Is it possible to automatically download a PDF file from a URL received through a $http GET() request from the server? The $http request is triggered by clicking a button on the front-end, and upon successful completion of the request, the URL where the PD ...

Personalize your Datatable export options with Jquery

I am working with a datatable that contains columns with data in the format 'XXXX unit'. For my export, I need to remove the 'unit' part of the data. What specific rule should I implement for this task? exportOptions: { columns: ...