-
-
Notifications
You must be signed in to change notification settings - Fork 3.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat(frameworks): add @auth/fastify #9587
base: main
Are you sure you want to change the base?
Conversation
Ported express package to fastify and added the integration test for login.
The latest updates on your projects. Learn more about Vercel for Git ↗︎
1 Skipped Deployment
|
@hillac is attempting to deploy a commit to the authjs Team on Vercel. A member of the Team first needs to authorize it. |
@ianschmitz How does this compare to the method you used? |
I didn't get a chance to take it all the way to production, so I don't think I have a ton of feedback to give |
So first of all, thanks for contributing this! I'm working on a fastify application as we speak and had been putting off integrating Auth.js 😂 Anyway, I did some testing and it seems it's having an issue with esm/cjs and {"level":50,"time":1705315403580,"pid":1221767,"hostname":"ndo4","err":
{"type":"Error","message":"No \"exports\" main defined in /opt/ndomino/sveltekasten-
rss/node_modules/@auth/core/package.json","stack":"Error [ERR_PACKAGE_PATH_NOT_EXPORTED]:
No \"exports\" main defined in /opt/ndomino/sveltekasten-
rss/node_modules/@auth/core/package.json\n at __node_internal_captureLargerStackTrace
(node:internal/errors:497:5)\n at new NodeError (node:internal/errors:406:5)\n at
exportsNotFound (node:internal/modules/esm/resolve:268:10)\n at packageExportsResolve
(node:internal/modules/esm/resolve:542:13)\n at resolveExports
(node:internal/modules/cjs/loader:547:36)\n at Module._findPath
(node:internal/modules/cjs/loader:621:31)\n at Module._resolveFilename
(node:internal/modules/cjs/loader:1034:27)\n at a._resolveFilename
(/opt/ndomino/sveltekasten-
rss/node_modules/.pnpm/[email protected]/node_modules/tsx/dist/cjs/index.cjs:1:1729)\n at
Module._load (node:internal/modules/cjs/loader:901:27)\n at Module.require
(node:internal/modules/cjs/loader:1115:19)\n at require
(node:internal/modules/helpers:130:18)\n Looks like its trying to resolve an import via esm/resolve helper, then falling back to cjs loader and then failing.. My fastify application is rather simple/straightforward atm and all ESM as far as I can tell
Here's my entrypoint file, I've checked out your branch, built the fastify adapter and import Fastify from "fastify"
import { dirname, join } from "path"
import { fileURLToPath } from "url"
import { updateJob } from "@jobs/cron-update"
import autoLoad from "@fastify/autoload"
import formbodyParser from "@fastify/formbody"
import GitHub from "@auth/fastify/providers/github"
import { FastifyAuth } from "@auth/fastify"
const fastify = Fastify({ logger: { level: "warn" } })
const _dirname = dirname(fileURLToPath(import.meta.url))
fastify.register(formbodyParser)
fastify.register(
FastifyAuth({
providers: [
GitHub({
clientId: process.env.GITHUB_ID,
clientSecret: process.env.GITHUB_SECRET,
}),
],
}),
{ prefix: "/api/auth" },
)
fastify.register(autoLoad, {
dir: join(_dirname, "routes"),
})
fastify.register(autoLoad, {
dir: join(_dirname, "plugins"),
})
;(async function () {
const port = process.env.PORT ? parseInt(process.env.PORT) : 8000
try {
await fastify.listen({ port, host: "0.0.0.0" })
console.log(`
🚀 Server ready at: http://0.0.0.0:${port}
⌛ Next cron run at: ${updateJob.nextRun()}
`)
} catch (err) {
fastify.log.error(err)
process.exit(1)
}
})() Am I missing anything? What did your example / development application look like and how did you run it? Maybe this is just a |
@ndom91 Here is a demo: https://github.com/hillac/authjs-fastify-demo Also, as was discussed with @auth/express, it might be nicer for users if the auth decorator is part of @auth/fastify in the plugin. I left it out for now to copy @auth/express. |
@hillac okay great, thanks for the repo example. Turns out I was just having some issues with the fastify autoload plugin. Seems to all work now! |
Regarding your question about the decorator - while I agree, we should try to get as much as possible in the plugin itself, this |
Also looks like the |
Checklist for us before merging:
Did I miss anything? CC: @ThangHuuVu |
Is there any reason I cant do the dev app in a separate pr like was done for qwik? |
any update on this? |
Hi. I'd like to integrate auth.js in my fastify app and saw this PR has been frozen for months. @hillac do you want to continue working on this? If not, I can fork this and continue the work (setting up examples etc.) |
@songkeys feel free to make a pr to my repo and ill merge it into this pr. I have a half complete example app Ill push. I just cloned the express one and switched everything for fastify. I gave up on getting this pr through and have just been using @auth/core with the adapter from this PR directly in my project. |
See hillac#1 |
feat: add fastify example
@ndom91 Just added examples. Could you please take a look? |
There are some conflicts on this PR, could you check them @hillac ? |
This would be fantastic to get merged! 🙏 |
I don't know how to get the maintainer's attention. If you want to use this anytime soon you'll have to just publish your own package or copy paste it into your project as I'm doing. |
☕️ Reasoning
This PR is a port of @rexfordessilfie's @auth/express to Fastify. It uses similar translation layer with Web API Request and Response to fastify types. I opted to make it a plugin.
Implementation
toWebRequest
helper that converts anFastifyRequest
into a webtoFastifyReply
helper that converts a webRequest
into anFastifyReply
FastifyAuth(authConfig)
initializer which returns a fastify plugin function of typeFastifyPluginAsync
to fulfill authentication requests. Under the hood, it:toWebRequest(request)
to get a webRequest
Auth
(from@auth/core
) to get back a webResponse
reply
totoFastifyReply(response, reply)
to respond to fulfill the requestTests
toWebRequest
andtoFastifyReply
helpers to ensure that they forward all headers, and body and in the right format (depending on content-type)getSession
by mocking the sessionDocumentation
I still haven't finished converting the express docs to fastify, just the main example is done so far.Notes
In the docs, I've added the trust proxy for the https issue. I've yet to test if this is actually required in fastify.
For the async handlers, I've used
return body
instead ofreply.send(body)
. I'm not sure whats preferred.The body is unknown type in
FastifyRequest
so I checkedtypeof req.body === 'object' && req.body !== null
inencodeRequestBody
. I'm not sure if this is ok. In order to testencodeUrlEncoded
, I had to add checks for the body type.For the response tests, the fastify injector returned the body as a string, so I had to stringify the expected value in the test equality. It also added
; charset=utf-8
to the end of the content type header, so I stripped that off for the test equality. I'm not sure if this is an issue.@fastify/formbody
might need to be a peer dependency, I'm not sure.🧢 Checklist
🎫 Affected issues
📌 Resources