A collection of example projects built with Lucia.
lucia-auth / examples Goto Github PK
View Code? Open in Web Editor NEWA collection of example projects built with Lucia
License: MIT License
A collection of example projects built with Lucia
License: MIT License
A collection of example projects built with Lucia.
switched from next.js to remix so curious.
any reason for that? does remix not gel well with lucia or is remix-auth
recommended?
There is no example and no documentation on how to use google oauth with lucia.
I recently integrated lucia auth into my application with google provider, specifically Google from "arctic".
I could help out with the examples and the documentation.
Everything from environment variables, setting up prisma orm to setting up scopes and all will be covered.
Steps
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
)Please update @solidjs/start and vinxi in the packages because it doesn't work because of them.
I'm not able to go to "/" even when i'm connected. (The page is protected by a middleware)
I am trying to utilize next middleware to redirect user if not login.
Here is my middleware file
import {
DEFAULT_LOGIN_REDIRECT,
PUBLIC_ROUTES,
AUTH_ROUTES,
API_AUTH_PREFIX,
LOGIN_REDIRECT,
} from "@/routes";
import { NextRequest } from "next/server";
import { validateRequest } from "@/lib/lucia";
export async function middleware(req: NextRequest) {
const { user } = await validateRequest();
const isLogin = true;
const { nextUrl } = req;
const isApiAuthRoute = nextUrl.pathname.startsWith(API_AUTH_PREFIX);
const isAuthRoute = AUTH_ROUTES.includes(req.nextUrl.pathname);
const isPublicRoute = PUBLIC_ROUTES.includes(req.nextUrl.pathname);
if (isApiAuthRoute) {
return;
}
if (isAuthRoute) {
if (isLogin) {
return Response.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl));
}
return;
}
if (!isLogin && !isPublicRoute) {
return Response.redirect(new URL(LOGIN_REDIRECT, nextUrl));
}
return;
}
export default middleware;
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};
Here is my validate validateRequest()
export const validateRequest = cache(
async (): Promise<
{ user: User; session: Session } | { user: null; session: null }
> => {
const sessionId = cookies().get(lucia.sessionCookieName)?.value ?? null;
if (!sessionId) {
return {
user: null,
session: null,
};
}
const result = await lucia.validateSession(sessionId);
// next.js throws when you attempt to set cookie when rendering page
try {
if (result.session && result.session.fresh) {
const sessionCookie = lucia.createSessionCookie(result.session.id);
cookies().set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
}
if (!result.session) {
const sessionCookie = lucia.createBlankSessionCookie();
cookies().set(
sessionCookie.name,
sessionCookie.value,
sessionCookie.attributes
);
}
} catch {}
return result;
}
);
Whenever I use this validateRequest()
func in my middleware, I get an error
Module build failed: UnhandledSchemeError: Reading from "cloudflare:sockets" is not handled by plugins (Unhandled scheme). Webpack supports "data:" and "file:" URIs by default. You may need an additional plugin to handle "cloudflare:" URIs.
I'm trying to get this example working with Deno and Hono while being pretty new to typescript etc. so sorry if this issue is obvious.
I first changed some tiny things in lib to get it compiling with Deno. Then I started on routes/, and I now get this warning from deno check
:
error: TS2339 [ERROR]: Property 'username' does not exist on type 'User'.
const html = template.replaceAll("%username%", user.username).replaceAll("%user_id%", user.id)
From that it seems like deno is picking up at least some of the types for Lucia but the User type is not as expected or is not correct somehow. I am wondering what is the mechanism by which the username property is expected to be pulled in? I see that username is a db field but don't understand the mechanism by which it becomes a property of User in this context. I think maybe in this context User is actually known to be of a descendant type and I also need to tell typescript about this somehow?
Any advice appreciated
In the following code:
needs to be:
<form method="post" use:enhance >
so that the form trigger the defauls action in defined in +page.server.ts
Error when calling server action in a project using lucia auth.
⨯ node_modules/lucia/dist/core.js (26:61) @ new Lucia
⨯ TypeError: oslo__WEBPACK_IMPORTED_MODULE_0__.TimeSpan is not a constructor
at eval (./lib/auth.ts:24:15)
at (action-browser)/./lib/auth.ts (/home/rodrigo/Web_dev/FullStack_projects/Tailwind/examples-lucia-v3/nextjs-app/username-and-password/.next/server/app/test/page.js:330:1)
at __webpack_require__ (/home/rodrigo/Web_dev/FullStack_projects/Tailwind/examples-lucia-v3/nextjs-app/username-and-password/.next/server/webpack-runtime.js:33:42)
at eval (./lib/actions.ts:9:67)
at (action-browser)/./lib/actions.ts (/home/rodrigo/Web_dev/FullStack_projects/Tailwind/examples-lucia-v3/nextjs-app/username-and-password/.next/server/app/test/page.js:319:1)
at Function.__webpack_require__ (/home/rodrigo/Web_dev/FullStack_projects/Tailwind/examples-lucia-v3/nextjs-app/username-and-password/.next/server/webpack-runtime.js:33:42)
Steps to reproduce:
import DummyForm from "./dummy-form";
export default async function DummyPage() {
return (
<main className="flex items-center justify-center h-screen w-screen">
<h1>Dummy Form</h1>
<DummyForm />
</main>
);
}
"use client";
import { dummy } from "@/lib/actions";
export default function DummyForm() {
console.log("DummyForm client");
return (
<form action={dummy} className="space-y-3">
<input
type="hidden"
id="Hiddenfield"
name="Hiddenfield"
value="value"
></input>
<button>Click Me</button>
</form>
);
}
"use server";
export async function dummy(formData: FormData) {
console.log("dummy", formData);
}
import { lucia, validateRequest } from "@/lib/auth";
export interface ActionResult {
error: string | null;
}
export async function dummyAuth( formData: FormData ) {
const { session } = await validateRequest();
}
Any idea as to why this happens?
Hi there, would you consider creating a basic React example? Without framework specifics like nextjs.
I use React, with vite for tooling
Many thanks!
At the moment, using mongoose with the mongodb adapter doesn't work.
insertOne() doesn't exist in mongoose.
mongoose uses create() instead.
line 58 :
replacing await this.Session.insertOne(value); // MUST be replaced for Mongoose
by await this.Session.create(value); // WORKS for Mongoose
does the trick for mongoose but won't probably work for mongodb adapter.
Maybe using the save()
collection method which I believe works both in mongoose and mongodb could be the simplest solution to avoid creating a dedicated mongoose adapter ?
i was getting lots of requests for a session
that won't change on my dashboard when i switched between 3 tabs.
ideally, it should only request session 1 time but it requested 3 times.
so i asked chatgpt for optimization & it found one:
export const getPageSession = cache(async () => {
const authRequest = auth.handleRequest("GET", context)
const session = await authRequest.validate()
return session
})
i checked it & it does send only 1 request.
using next.js example btw :)
I am looking at the functions generateEmailVerificationToken and generatePasswordResetToken, both first looking if a token exists, and if not generating a new one. Both return the id of the token if an existing one is found, probably not correct, or is it? They should return the found token string and not its id, am I right?
lines 18 and 65
I would like to know how to use lucia auth to validate routes in the middleware level in NextJS 14.1
White starting the Stackblitz Sveltekit Demo an error occurs.
https://stackblitz.com/github/lucia-auth/examples/tree/main/sveltekit/username-and-password?file=README.md
Trying to use the astro examples with v4 fails.
09:47:00 [WARN] [router] No API Route handler exists for the method "GET" for the route /email-verification/[token...].
Found handlers: "get"
grep -r 'export const get:\|export const post:'
...
examples/astro/username-and-password/src/pages/logout.ts:export const post: APIRoute = async (context) => {
examples/astro/github-oauth/src/pages/login/github/index.ts:export const get: APIRoute = async (context) => {
examples/astro/github-oauth/src/pages/login/github/callback.ts:export const get: APIRoute = async (context) => {
examples/astro/github-oauth/src/pages/logout.ts:export const post: APIRoute = async (context) => {
examples/astro/email-and-password/src/pages/logout.ts:export const post: APIRoute = async (context) => {
examples/astro/email-and-password/src/pages/email-verification/[token].ts:export const get: APIRoute = async ({ params, locals }) => {
Replace the lowercase "get" and "post" with UC versions and it works with Astro V4.
Would be good to have some basic example. I like the minimalism of Lucia but sometimes it's confusing when everything is separated into small packages.
I don't want to use something like Hanko (they recently released standalone Passkeys API but not quite getting it), or the Exodus' Passkeys Wallet (passkeys.foundation, @passkeys/core
) which is 2mb just npm package without actual source code.
I am having trouble with the nextjs app router + username-and-password example,
Expected Behavior:
Actual Behavior:
I found this guide: https://preview.lucia-auth.com/guidebook/github-oauth-native/expo/
which referred to: https://github.com/lucia-auth/examples/tree/main/expo/github-oauth
Has it been relocated perhaps?
Hi! 👋
I've been using Lucia for a couple of Astro projects and love how it just works and the overall the DX!
Updating the examples to Astro 4 would be awesome to keep up with the latest features 🧑🚀 🚀
I've opened a PR #19 to update to Astro v4 and astrojs/node v8. All examples are working as expected 😄
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.