The module './$types' or its related type declarations could not be located in server.ts

Issue with locating RequestHandler in +server.ts file despite various troubleshooting attempts (recreating file, restarting servers, running svelte-check)

+server.ts development code:

import type { RequestHandler } from './$types'
/** @type {import('./$types').PageServerData} */
export const POST = (async ({ clientAddress, request, url }: { clientAddress: string, request: Request, url: string }) => {
  console.log(request.body)
  try {
    const res = await fetch('http://localhost:8787/', {
      method: 'POST',
      body: request.body
    })
    if (!!res.ok) {
      const data = await res.json()
      console.log('data: ', data)
    }
  } catch(e) {
    return new Response(JSON.stringify({ message: 'Error: ', e }), { status: 500 })
  }
  return new Response(JSON.stringify({ message: 'Success' }), { status: 200 })
}) satisfies RequestHandler 

svelte.config.js config:

import adapter from '@sveltejs/adapter-cloudflare';
import { vitePreprocess } from '@sveltejs/kit/vite';

/** @type {import('@sveltejs/kit').Config} */
const config = {
    preprocess: vitePreprocess(),
    kit: {
        adapter: adapter(),
    }
};

export default config;

vite.config file settings:

import { sveltekit } from '@sveltejs/kit/vite'
import { defineConfig } from 'vitest/config'

export default defineConfig({
    plugins: [sveltekit()],
    resolve: {
        alias: {
            $lib: '/src/lib',
            $routes: '.svelte-kit/types/src/routes',
        }
    },
    test: {
        include: ['src/**/*.{test,spec}.{js,ts}']
    }
})

Additonally encountering the error:

Cannot find module '@sveltejs/kit/vite' or its corresponding type declarations.ts(2307)

Persistent issues with new sveltekit installation despite attempted solutions.

Answer №1

Ensure that your +server.ts file is located within the routes directory.

I encountered a similar issue when I mistakenly placed the +server.ts in the /lib/api folder instead of the /routes/api folder.

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

Steps to have index.html display when running the build command in a Svelte project:

Greetings everyone, I'm brand new to using Svelte and have a question that's been on my mind. I recently developed a small app in Svelte that works perfectly fine during development. However, when I run npm run build for production, the output ...

What is the best way to have an icon appear when a child component div is clicked, without it displaying on other similar divs?

Within my child component div, I have configured it to display information from an object located in the parent component. Initially, when the web app loads, it correctly shows three divs with names and messages retrieved from the created object. However, ...

Access PDF document in a fresh tab

How can I open a PDF file in a new tab using Angular 6? I have tried the following implementation: Rest controller: @RestController @RequestMapping("/downloads") public class DownloadsController { private static final String EXTERNAL_FILE_PATH = "/U ...

7 Tips for Renaming Variables in VSCode without Using the Alias `oldName as newName` StrategyWould you like to

When working in VSCode, there is a feature that allows you to modify variables called editor.action.rename, typically activated by pressing F2. However, when dealing with Typescript and Javascript, renaming an imported variable creates aliases. For exampl ...

What is the reason for not hashing the password in this system?

My password hashing code using Argon2 is shown below: import { ForbiddenException, Injectable } from '@nestjs/common'; import { PrismaService } from 'src/prisma/prisma.service'; import { AuthDto } from './dto'; import * as arg ...

Guide on Executing a Callback Function Once an Asynchronous For Loop Completes

Is there a way to trigger a callback function in the scan function after the for await loop completes? let personObj = {}; let personArray = []; async function scan() { for await (const person of mapper.scan({valueConstructor: Person})) { ...

Using immer JS to update a nested value has been successfully completed

What is the most efficient way to recursively change a value using a recursive function call in a Produce of Immer? The WhatsappState represents the general reducer type, with Message being the message structure for the application/db. type WhatsappState = ...

What determines the narrowing of a type when it is defined as a literal versus when it is returned from a function?

I'm really trying to wrap my head around why type narrowing isn't working in this scenario. Here's an example where name is successfully narrowed down: function getPath(name: string | null): "continue" | "halt" { if (n ...

"Encountered a 'NextAuth expression cannot be called' error

Recently, I delved into learning about authentication in Next.js using next-auth. Following the documentation diligently, I ended up with my app/api/auth/[...nextauth]/route.ts code snippet below: import NextAuth, { type NextAuthOptions } from "next-a ...

The 'Subscription' type does not contain the properties _isScalar, source, operator, lift, and several others that are found in the 'Observable<any>' type

Looking to retrieve data from two APIs in Angular 8. I have created a resolver like this: export class AccessLevelResolve implements Resolve<any>{ constructor(private accessLevel: AccessLevelService) { } resolve(route: ActivatedRouteSnapshot, sta ...

Transition from using ReactDOM.render in favor of asynchronous callback to utilize createRoot()

Is there a React 18 equivalent of this code available? How does it handle the asynchronous part? ReactDOM.render(chart, container, async () => { //code that styles some chart cells and adds cells to a worksheet via exceljs }) ...

Is there a way to dynamically adjust the size of an image in NodeJS utilizing Sharp, when only provided with a URL, employing async/await, and ensuring no local duplicate is

In my current work environment, the only image processing library available is NodeJS's Sharp for scaling images. It has been reliable due to its pipe-based nature, but now I have been given the task of converting it to TypeScript and utilizing Async/ ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

Having trouble showing table data in Angular

My goal is to showcase data from a table created using Spring-Boot Below is my model.ts: export class Quiz1 { QuestionId?: any; Question?: string; OptionsA?: string; OptionsB?: string; OptionsC?: string; OptionsD?: string;} He ...

How can Node / Javascript import various modules depending on the intended platform?

Is there a way to specify which modules my app should import based on the target platform in TypeScript? I am interested in importing different implementations of the same interface for a browser and for Node.js. In C++, we have something like: #ifdef wi ...

The TypeScript compiler is generating node_modules and type declaration files in opposition to the guidelines outlined in the tsconfig.json file

For the past week, I've been trying to troubleshoot this issue and it has me completely puzzled. What's even more puzzling is that this app was compiling perfectly fine for months until this problem occurred seemingly out of nowhere without any c ...

Vitek - Uncaught ReferenceError: Document Is Not Defined

Why am I encountering an error when trying to use File in my vitest code, even though I can typically use it anywhere else? How can I fix this issue? This is the content of my vite.config.ts. /// <reference types="vitest" /> import { defin ...

What are some ways to specialize a generic class during its creation in TypeScript?

I have a unique class method called continue(). This method takes a callback and returns the same type of value as the given callback. Here's an example: function continue<T>(callback: () => T): T { // ... } Now, I'm creating a clas ...

Define the data type for the toObject function's return value

Is it possible to define the return type of the toObject method in Mongoose? When working with generics, you can set properties of a Document object returned from a Mongoose query. However, accessing getters and setters on these objects triggers various v ...

Issue with rejecting a promise within a callback function in Ionic 3

Within my Ionic 3 app, I developed a function to retrieve a user's location based on their latitude and longitude coordinates. This function also verifies if the user has location settings enabled. If not, it prompts the user to switch on their locati ...