#Can you create an endpoint that returns JavaScript code that is processed and bundled by Astro?

3 messages · Page 1 of 1 (latest)

granite hemlock
#

So my use case is: I want to offer other websites the opportunity to include a JS file that is generated by our Astro site. So website xyz.com will include <script src="our-astro-site.com/example.js" />.
Therefore, I want to create an enpoint in src/pages/example.js.js . This endpoint should respond with a JS file. I can do this now like so:

export const testFunc = () => {
    console.log('test');
};

export async function get({ params, request }) {
    return new Response('(' + testFunc.toString() + ')()');
}

Which will work. The external site will log "test". But my issue is that all the JS code that this endpoint returns will not be processed/bundled by Astro. I would like to use the full JS authoring experience here (loading modules, minifying, etc.).

How can I make this work?

waxen elbowBOT
#

Hi @granite hemlock. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the extracts, Astro does not currently support the processing or bundling of JavaScript code returned from an endpoint. The code you return from an endpoint is sent as-is and is not processed by Astro's build system.

Astro's endpoints are designed to return data, not processed JavaScript files. They are typically used to create custom routes that return JSON, XML, or other types of data. They can also be used to create API routes that listen for requests and execute code on the server at runtime.

Here is an example of how you might create an endpoint that returns JSON data:

// Example: src/pages/builtwith.json.ts
// Outputs: /builtwith.json

export async function get() {
 return {
 body: JSON.stringify({
 name: "Astro",
 url: "<https://astro.build/",>
 }),
 }
}

(Source: Astro 0.23 Release Notes (https://astro.build/blog/astro-023/))

If you need to serve a processed JavaScript file, you might consider creating the file as part of your build process and serving it as a static asset. However, this approach is not covered in the provided extracts.

For more information on how to use endpoints in Astro, you can refer to the Astro documentation on endpoints (https://docs.astro.build/en/core-concepts/endpoints/).

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: