matthewp / astro-fastify Goto Github PK
View Code? Open in Web Editor NEWA Fastify adapter for Astro
A Fastify adapter for Astro
When I follow the instructions for adding astro-fastify
to an existing (minimal) Astro app, then run pnpm run build
, I get this error:
error Cannot read properties of null (reading 'closeAllConnections')
File:
/path/to/node_modules/.pnpm/[email protected]/node_modules/fastify/fastify.js:192:54
I traced that to server.httpServer
being null
in serverFactory
.
Is there configuration I'm missing?
Sorry if this is not the right place to post this, but I don't know what else this error might refer to, I already tried asking the fastify community on Discord.
I get this error when registering the plugin @fastify/cors :
node_modules\fastify\lib\route.js:306
throw new FST_ERR_DUPLICATED_ROUTE(opts.method, opts.url)
^
FastifyError [Error]: Method 'OPTIONS' already declared for route '*'
at Object.addNewRoute (...\node_modules\fastify\lib\route.js:306:19)
at Object.route (...\node_modules\fastify\lib\route.js:217:19)
at Object.prepareRoute (...\node_modules\fastify\lib\route.js:150:18)
at Object._options [as options] (...\node_modules\fastify\fastify.js:264:34)
at fastifyCors (...\node_modules\@fastify\cors\index.js:42:11)
at Plugin.exec (...\node_modules\avvio\plugin.js:130:19)
at Boot.loadPlugin (...node_modules\avvio\plugin.js:272:10)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
code: 'FST_ERR_DUPLICATED_ROUTE',
statusCode: 500
}
The problem is that I didn't register the route '*' so I don't know how to fix that.
Edit:
I found these pieces of code in your adapter, I think they are causing the error (?)
Line 60 in 482d3a3
Line 53 in 482d3a3
Hi, I'm trying to build for production, but I get this error when I do astro check && tsc --noEmit && astro build
:
[vite]: Rollup failed to resolve import "C:UsersdanynDocumentsGitHubexplorershandbook
[email protected]" from "@astrojs-ssr-virtual-entry".
This is most likely unintended because it can break your application at runtime.
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
I did what he said:
vite: {
build: {
rollupOptions: {
external: fileURLToPath(new URL('node_modules/@matthewp/astro-fastify/lib/server.js', import.meta.url))
}
}
}
But I still get the error.
The following is the code my entry points to:
import type { FastifyCookieOptions } from '@fastify/cookie';
import type { DefineFastifyRoutes } from '@matthewp/astro-fastify';
import { fastifyTRPCPlugin } from '@trpc/server/adapters/fastify';
import { createApiContext } from './api-context.js' // fails;
import { env } from './env.js'; // fails
import { apiRouter } from './routes/index.js'; // fails
const defineRoutes: DefineFastifyRoutes = async (fastify) => {
const cookieOption: FastifyCookieOptions = {
secret: env.JWT_SECRET,
}
fastify
.register(import('fastify-graceful-shutdown'))
.register(import('@fastify/websocket'))
.register(import('@fastify/cookie'), cookieOption)
.register(import('@fastify/csrf-protection'))
.register(fastifyTRPCPlugin, {
prefix: '/trpc',
useWSS: true,
trpcOptions: { router: apiRouter, createContext: createApiContext },
})
};
export default defineRoutes;
All the local imports fail with:
Failed to load url ./api-context.ts (resolved id: ./api-context.ts). Does the file exist?
Do you know what's happening?
I'm trying to decide if this is just a documentation issue or if there's something else going on. Starting a brand new Astro project via npm create astro@latest
and then attempting to add this dependency, throws an error:
Cannot find module '/home/jim/Sites/ostk-header/api/index.js' imported from /home/jim/Sites/ostk-header/node_modules/@matthewp/astro-fastify/lib/index.js
Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/jim/Sites/ostk-header/api/index.js' imported from /home/jim/Sites/ostk-header/node_modules/@matthewp/astro-fastify/l
ib/index.js
at new NodeError (node:internal/errors:393:5)
Well that's simple enough, right? We named the file api/index.ts
. So, let's change that in the config:
import fastify from '@matthewp/astro-fastify';
/** @type {import('astro').AstroUserConfig} */
export default {
output: 'server',
adapter: fastify({
entry: new URL('./api/index.ts', import.meta.url)
})
};
But that'll throw:
Unknown file extension ".ts" for /home/jim/Sites/ostk-header/api/index.ts
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/jim/Sites/ostk-header/api/index.ts
at new NodeError (node:internal/errors:393:5)
at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:80:11)
at defaultGetFormat (node:internal/modules/esm/get_format:122:38)
As we're trying to us ESM imports, not Typescript. So let's try naming the file index.js
. From the presence of a type definition, it looks like you really did mean for it to be Typescript though. Regardless, that doesn't work.
Finally, let's name the file .mjs
and change the reference to ./api/index.mjs
. THAT seems to work. I don't think that was your intention though. I really do think you wanted to use Typescript so... what might I be missing here?
I have the following code:
const defineRoutes: DefineFastifyRoutes = (fastify) => {
fastify.register(import("@fastify/formbody"));
}
I ran:
pnpm build
node ./dist/server/entry.mjs
This code seems to throw the follwoing:
{"statusCode":500,"error":"Internal Server Error","message":"Response body object should not be disturbed or locked"}
When I had a post request to:
import {
serverRouteClient,
serverRouteClientServiceRole,
} from "@supabase/instances";
import type { APIRoute } from "astro";
import { z } from "zod";
export const POST: APIRoute = async ({ request, cookies, url, redirect }) => {
console.log("signup");
const supabase = serverRouteClient(cookies);
const body = await request
.formData()
.then(Object.fromEntries)
.then(
z.object({
email: z.string().email(),
password: z.string(),
passwordConfirmation: z.string(),
}).parseAsync,
);
if (body.password != body.passwordConfirmation) {
throw new Error("Confirmation password didn't match the actual password");
}
const res = await supabase.auth.signUp({
email: body.email,
password: body.password,
options: {
emailRedirectTo: `${url.origin}/auth/callback`,
},
});
if (res.error) {
return new Response(res.error.message, { status: res.error.status });
}
if (!res.data.user?.id) {
return new Response("Failed to create a user", { status: 500 });
}
return redirect("/");
};
I have the following configuration:
import { defineConfig } from "astro/config";
import react from "@astrojs/react";
import tailwind from "@astrojs/tailwind";
import fastify from "@matthewp/astro-fastify";
// https://astro.build/config
export default defineConfig({
integrations: [react(), tailwind()],
output: "server",
adapter: fastify({
entry: new URL("./server-entry.ts", import.meta.url),
}),
server: {
port: +(process.env.PORT || 4321),
},
});
Why is the adapter not supporting sharp?
The currently selected adapter
@matthewp/astro-fastify:adapter is not compatible with the image service "Sharp"
How can I help make it compatible to sharp?
The Module is not working with Astro 4.0.
Astro throws this error.
The adapter @matthewp/astro-fastify:adapter doesn't provide a feature map. It is required in Astro 4.0.
For example, when you set Astro.request.headers.set('test-header', 'test-1');
from a layout file, it should also affect Fastify, IMO.
https://docs.astro.build/en/guides/server-side-rendering/#astrorequestheaders
hi @Matthew2 , just found out in the SSR adapter for fastify the following lines:
Why would we do that? Is there a reason behind? I'm compressing the data on a reverse proxy and because of this header it simply does not compress anything.
It also seems like an obsolete action, this header is not anyhow required AFAIK
Do I miss something?
Thanks a lot!
Possible workaround:
Currently I reset the content-type header to actually bypass this condition
Astro.response.headers.set('Content-Type', 'text/html; charset=utf-8');
Maybe I'm missing something, but hot reloading doesn't seem to work for fastify routes.
I'm trying to register logger serializers for Fastify inside astro.config.mjs
and they work in dev mode, but when I run astro build
, the resulting dist/server/entry.mjs
does not have the serializers configured inside it.
I tried to create a minimal example here: https://github.com/luiz/astro-fastify-logger-serializer
Hello and thanks for this adapter!
I'd like to be able to add Middleware to my astro endpoints. Eg. I'd like to add something like request.user
to the request that my astro endpoint processes.
I was excited by this adapter because it works in dev mode however I don't see a way to inject variables from a fastify middleware/or hook, (eg onRequest) so that it is available to my astro endpoints.
Is this possible?
Thanks
Hey @matthewp, I saw your youtube a while ago with Matt Collina in where you were adding Astro to an existing Fastify server. Is that something this can be used for? I want to use Astro as my templating system and Fastify as the routing system. Any guidance is appreciated. Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.