SvelteKit: Exploring alternative ways to interact with MongoDB without relying on traditional endpoints

(1/9/2023) Update: SvelteKit has recently introduced support for server-only load functions and Form actions to enable sending requests to the server.


I am looking to retrieve data from my database without allowing end users to access it through the API endpoint I have set up. I am curious about how I can directly query my database from a file within the lib folder and return the data accordingly. However, when attempting this approach, I encounter an error stating global not defined:

lib/db.js:

import dotenv from "dotenv";
dotenv.config();
import { MongoClient } from "mongodb";

const uri = process.env["MONGODB_URI"];
const options = {
  useUnifiedTopology: true,
  useNewUrlParser: true,
};

let client;
let clientPromise;

if (!uri) {
  throw new Error("Please add your Mongo URI to .env.local");
}

if (process.env["NODE_ENV"] === "development") {
  if (!global._mongoClientPromise) {
    client = new MongoClient(uri, options);
    global._mongoClientPromise = client.connect();
  }
  clientPromise = global._mongoClientPromise;
} else {
  client = new MongoClient(uri, options);
  clientPromise = client.connect();
}
export default clientPromise;

routes/items/index.js:

import clientPromise from "$lib/db";

export async function get() {
  const client = await clientPromise;
  const db = client.db();
  const data = await db.collection("items").find({}).toArray();
  const items = data.map(({ name }) => ({ name }));

  if (items) {
    return {
      body: {
        items,
      },
    };
  }
}

My attempt: lib/stores/items.js

import clientPromise from "$lib/db";
import { writable } from "svelte/store";
export const items= writable([]);

const fetchItems = async () => {
  const client = await clientPromise;
  const db = client.db();
  const data = await db.collection("items").find({}).toArray();
  const items = data.map(({ name }) => ({ name }));

  substances.set(items);
};

fetchItems();

Despite trying the aforementioned code in multiple locations, the recurring issue of global not defined persists on the client side.

I came across a similar query where someone faced the same problem, but I'm uncertain on how to create a helper file to address this issue.

Answer №1

Securing APIs is typically handled on the backend. This can be done using server-side technologies like NodeJS, or through tools such as Nginx/Apache (for proxying). If you're concerned about securing your API, you may want to explore topics related to Content Security Policy, although this is not directly relevant to SvelteKit.

By the way, attempting to access a database directly from the frontend would pose security risks and is generally not recommended.

Answer №2

One way to retrieve information from a database is by setting up an endpoint.

If you need to implement user authentication, consider using the handle hook:

export async function handle({ request, resolve }) {
  let user = await authenticate(request) 

  request.locals.user = user
  request.locals.isAuthenticated = !!user

  if (request.path.startsWith('/api')) {
    if (!user) {
      return {
        status: 401,
        body: JSON.stringify({
          error: {
            message: 'Unauthorized'
          }
        })
      }
    }

  const response = await resolve(request)
  return response
}

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

The next.js code is functioning properly when run in development mode, but encounters issues when attempting

When using the useAddress() function in run dev, it is returning undefined undefined and then the address when console logged. However, in the run build/start, it only returns undefined. What steps should I take to resolve this issue? import { useAddres ...

Working with real-time data in JavaScript to dynamically modify a JSON array

After making a request to an API, I receive a large JSON array. Using SignalR, I then obtain a smaller JSON array that only contains the objects from the API data that have been changed. My goal is to retrieve the modified objects from the API array and u ...

An error occurred when attempting to use the getDoc() function from Firebase within Next.js: TypeError - reading 'map' on properties of undefined

Hello everyone at StackOverflow, I ran into a problem while attempting to use .map() on a getDoc() constant in my Next.js application. The error message I'm getting is: "TypeError: Cannot read properties of undefined (reading 'map')". As a n ...

Organize a list in AngularJS by breaking it down based on its headers and displaying them in

As someone who is new to angularJs, I am looking to convert an app to angularJs but I have encountered a roadblock: The custom accordion markup I am working with is as follows: <div class="accord_main_wrap" ng-controller="catController"> <di ...

Remove all HTML tags except for those containing a specific class

Looking for a regex that removes all HTML tags except the "a" tags with the "classmark" class For example, given this HTML string: <b>this</b> <a href="#">not match</a> <a href="#" target="_blank" ...

Guide for pausing the React function until the fetch operation is completed

I am currently working with React js and facing an issue with rendering data fetched from an API using Fetch. The problem I'm encountering is that the return scope of React executes before the fetch method is completed! Can anyone provide assistance o ...

The canvas is being expanded by utilizing the drawImage method

Ensuring the correct size of a <canvas> element is crucial to prevent stretching, which can be achieved by setting the width and height attributes. Without any CSS applied other than background-color, I am faced with an unusual issue. Using ctx.draw ...

How to query multiple collections using different variables in mongoengine and Django

Can variable be used as part of a collection name to query different collections based on the name in mongoengine? For instance: Imagine having 3 collections in your mongoDB: collection_first collection_second collection_third and running a simple for ...

Invoking servlet using Ajax

I have created a JSP file with Javascript functions and AJAX calls to invoke a servlet (ReadprojectInfo). <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE ...

Adaptive Layout: rearranging the sequence of Div elements

I am having a simple webpage and I want to change the layout so that when the width is decreased, the "middle" div goes on top of the "left" div. Currently, the middle div is positioned below the left div, but I would like to make it overlap the left div. ...

Encountered an issue while executing the npm run dev command in a React project

Hello, I am a beginner with React.js and I am currently trying to set up a simple React application locally using webpack. However, when I run the npm run dev command, I encounter the following error: An error occurs in the command prompt after running np ...

Generate an array of arrays containing objects using different variable names

Here is the issue at hand: const data : [ {labelSlug: 'cola', category: 'catering', subCategory: 'drinks', provider: 'coca cola'}, {labelSlug: 'cola', category: 'catering', subCategory: 'drin ...

Shuffle order of AngularJS ng-repeat array

I am struggling to create a basic grammar quiz where I need to randomly sort an array using ng-repeat. The goal is to display both correct and incorrect sentences in random order. Below you can find my code snippet: (function(angular) { 'use str ...

Vue.js2 - Detection of Observer in Array

A question for beginners in vue.js. I am trying to display data using the CanvasJS Library that is received via websocket. Everything works fine with the data until I introduce vue components into the mix. Let me clarify: export default { data() { r ...

Half of the time, the Ajax request is returning the entire page

I have a dropdown select box in HTML that contains around 20 different number codes (e.g. "123456790") as options. When a selection is made, it triggers an Ajax POST request to update the text of a specific HTML element. The code looks like this: HTML &l ...

Encountered a MongoDB roadblock: E11000 error indicating a duplicate key conflict while attempting an upsert

It is my understanding that when performing an update with upsert:true on a single document, it should be an atomic operation and not result in a duplicate key error, especially for the primary _id key, when the collection does not have any uniquely indexe ...

Accessing a Mongodb instance within a docker container's network from a separate docker container

I'm attempting to establish a connection to a MongoDB instance running in a Docker container from another Docker container where my Node.js code is executed. To start the MongoDB Docker container, I used the following command: docker run --name my-l ...

JavaScript String Splitting with Regular Expressions

It's like the solution is right in front of me, but I just can't seem to see it. var expr = "-5+6.3x24"; console.log(expr.split(/([+\-x\/])/)); The expected output should be: ["-5", "+", "6.3", "x", "24"] I want to split the string ...

Outputting PHP variables in JavaScript is a common practice used to pass

I am struggling to use a variable in my JavaScript code. I have attempted a few methods but none seem to work. The variable I need to include in the JavaScript is option-<?php echo $option['product_option_id']; ?> Below is my current Java ...

I'm confused as to why my Vue 3 Composition API with Django REST JWT setup is executing 2 POST requests even though I'm only sending it once

After successfully sending a POST request with axios to the Django REST API for tokens, I receive a 200 response containing refresh and access tokens that are then stored in local storage. However, upon inspection of the network tab, I noticed there is a ...