# Avoid exposing SQL queries with Named Sources

## Introduction

Modern data and geospatial applications must use a lightweight and efficient architecture in order to be successful. The way CARTO achieves this is by acting as the geospatial backend between your application and your data warehouse, reducing the need for further backend services and simplifying the architecture.

However, this also comes with a challenge: **how will your application and CARTO communicate** in a flexible and deterministic way to request the right data?

The most straightforward way that you'll find in many examples is by using SQL queries directly in the code and in the API requests — And while using SQL is fine and desirable for many applications, it may represent a security risk for some organizations, that would rather avoid uncovering their business logic by exposing the SQL queries used by the app.

**In this guide you will learn** how to use [Named Sources](https://docs.carto.com/carto-user-manual/developers/named-sources) to communicate from your application to CARTO, completely avoiding the exposure of SQL queries.

{% hint style="success" %}
Regardless if you use SQL queries or Named Sources, CARTO is fully protected against SQL injection. This is achieved by using sanitized, native methods from the data warehouse, plus additional layers of protection in the CARTO APIs.
{% endhint %}

## Preparing the application

First, you will need a working CARTO application that uses SQL queries, such as the `query-accidents` [example](https://docs.carto.com/carto-for-developers/examples). Let's start with that one:

```bash
git clone https://github.com/CartoDB/deck.gl-examples.git
cd deck.gl-examples/query-accidents
npm install
npm run dev
```

Once you do this, the application should be running in your browser. Notice how in `index.ts:51` you can find SQL queries, that would be exposed to any user in the app.

We are going to use **Named Sources** to replace those SQL queries with references that CARTO will understand and translate backend-side. Feel free to create a copy of the application if you prefer having both side by side.

## Preparing the Named Sources

Check the [Named Sources documentation](https://docs.carto.com/carto-user-manual/developers/named-sources) to learn how to create Named Sources. You will need to create two Named Sources:

<table><thead><tr><th width="250">Name</th><th>SQL Statement</th></tr></thead><tbody><tr><td><strong>accidents</strong></td><td><code>SELECT * FROM carto-demo-data.demo_tables.riskanalysis_railroad_accidents WHERE year = @selectedYear</code></td></tr><tr><td><strong>accidents_by_state</strong></td><td><code>SELECT polygons.code_hasc as polygonid, any_value(polygons.geom) as geom, any_value(name) as state_name, count(points.year) count FROM carto-demo-data.demo_tables.usa_states_boundaries as polygons LEFT JOIN carto-demo-data.demo_tables.riskanalysis_railroad_accidents as points ON ST_INTERSECTS(polygons.geom, points.geom) AND year=@selectedYear GROUP BY polygons.code_hasc</code></td></tr></tbody></table>

Once you're done, you'll have two Named Sources like in this screenshot:

<figure><img src="https://3029946802-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FybPdpmLltPkzGFvz7m8A%2Fuploads%2Fgit-blob-a12cb886367f5f3e2ba930c28d49decb572eaa14%2FScreenshot%202024-11-22%20at%2010.15.20.png?alt=media" alt=""><figcaption></figcaption></figure>

## Adding the Named Sources to your token

Create a new [API Access Token following the documentation](https://docs.carto.com/carto-user-manual/developers/managing-credentials/api-access-tokens), and make sure to add two grants for your two Named Sources, just like this screenshot:

<figure><img src="https://3029946802-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FybPdpmLltPkzGFvz7m8A%2Fuploads%2Fgit-blob-967ba4c7534a167d484766426277ccc110be56e9%2FScreenshot%202024-11-22%20at%2010.16.54.png?alt=media" alt=""><figcaption></figcaption></figure>

## Replace your SQL queries by Named Sources

Great! All the ingredients are there, let's connect the dots and your application will be using Named Sources:

1. **First, replace the API Access Token in the `.env` file:** use the token that you created in the previous step, containing the grants for your Named Sources
2. **Modify your data sources in `index.ts` around line 48:** here's where we are replacing our SQL queries by our Named Sources. It should now look something like:

```typescript
function render() {
  const accidentsByState = vectorQuerySource({
    ...cartoConfig,
    sqlQuery: 'public_example_accidents_by_state',
    queryParameters: {selectedYear: selectedYear}
  });

  const accidents = vectorQuerySource({
    ...cartoConfig,
    sqlQuery: 'public_example_accidents',
    queryParameters: {selectedYear: selectedYear}
  });

  // ... continues with const layers = [
```

## Run your application

**🎉 That's it, congrats!** If you now run the app:

```bash
npm run dev
```

You will see how the functionalities haven't changed at all, the map displays beautifully, and there's not a single SQL query being used in the application or exposed in the network requests.

* The final result for this guide can be found in the [CARTO for Developers examples](https://docs.carto.com/carto-for-developers/examples).
* Remember that you can [manage Named Sources programmatically via API](https://docs.carto.com/carto-user-manual/developers/named-sources#named-sources-api) for large-scale applications.

<figure><img src="https://3029946802-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FybPdpmLltPkzGFvz7m8A%2Fuploads%2Fgit-blob-5e9b2f34bef39d3093cf9041e50cef826dfdf6e0%2FScreenshot%202024-11-22%20at%2010.26.00.png?alt=media" alt=""><figcaption></figcaption></figure>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.carto.com/carto-for-developers/guides/avoid-exposing-sql-queries-with-named-sources.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
