-
Notifications
You must be signed in to change notification settings - Fork 389
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
v3 Beta #1235
Comments
Would using the middleware automatically refresh tokens? |
Thanks for shipping this update! 🎉 Just to follow up on what Tom said, it'd be great to get some guidance/workarounds on ways to mitigate those limitations. Seeing as the App Router is the future of next.js, it's safe to assume most people will move to adopt it and certainly new projects will be built on it by default. If they also want to adopt Auth0, the question then is how to make that work. In our case, we refresh our access tokens, so it'd be great to know how to work around this so that we aren't refreshing on every server page render once the access token has expired (which is what sounds like will happen). If the answer to @tomsseisums question is yes then we'd be happy to deploy that as a solution! |
Hi @lostinpatterns @tomsseisums To mitigate the issue of a rolling session not being updated in server components, I would recommend using To mitigate the issue with ATs not being refreshed, I would recommend using route handlers to get access token's and access 3rd party APIs. This should cover the majority of use cases. We don't support refreshing ATs on the edge yet - we have a different issue open for that #912 - I can't tell you when we might be able to prioritise work for this. |
Thank you for the swift beta release. I have one comment, I can open a separate issue if needed: The example app in the repo sets up middleware which is what I'd prefer to use, however the example app seems to be using both pages and app dir, and points the middleware initialization to the pages router version of the login. At first glance I thought I was supposed to use both pages and app /api/auth/[auth0] handlers to get the middleware to work. Would be nice to have an app router only example. Edit: Opened an issue I'm encountering using the beta in a fresh app here |
@jalvarado91 - see #1218 (comment) |
Great work on the beta! |
Thanks of the work on the beta. However, I get 500 errors whenever I visit any auth route after setting up the route.js file in the correct place. Any ideas how I can debug? I can't even get anything logging in console. I have duplicated the example repo and get exactly the same issue. |
I'd like to ask when v3 is expected to be released, I'm using the Beta version and the convenience of getting the AccessToken in the server component is a particularly useful feature for me. |
@danlutz, yes - the example app uses both the app router and the page router
@lewisking - the SDK should log errors to the console by default. If you're not even getting those you must have a more fundamental issue. Raise a new gh issue and share a reproducible example and I'd be happy to investigate.
@ZainChen (and to any future questions about release timing) - I can't give you a release date, but it will be at least 2 - 3 weeks away. |
I'm having the same issue as @lewisking: Can be reproduced with npx create-next-app@latest and the basic setup for @auth0/nextjs-auth0@beta |
@adamjmcgrath thanks Adam, was going to create one but just seen @jalvarado91 has created one in the meantime. Let's track the issues there as it's exactly what I'm getting. |
Works beautifully with my next 13.4.5 project! Haven't noticed any bugs yet, will report if I will |
Same here, server-components work like a charm! How do I get the accessToken from a client-component now, though? 🙈 Background: I want to connect to an external API with a Bearer token from auth0. Do I need to create proxy-routes now? |
@DotCoyote - see #358 (comment) |
Does anyone have any info on how to refresh the session.user from useUser()? When I update a user's role (from the api or the dashboard, wherever) it is not reflected in the session.user object. We used to have a custom handler in handleAuth (with the old req and res) that would do it but now I can't seem to get it working with app directory. I feel like there has got to be an easier way to simply update the user object than making a custom handler. Anyone have some insight? |
Can I use getSession in middleware? I get the following error: `Server Error This error happened while generating the page. Any console logs will be displayed in the terminal window. |
@lewisking See this one: #1247 |
Could you please give an example of how to use export const GET = withApiAuthRequired(
async (request: NextRequest, _context: RouteContext) => {
try {
const session = await getSession();
const response = NextResponse.redirect(new URL("/destination", request.url));
await updateSession(request, response, { ...session, user: { ...session?.user, name: "UPDATED" } });
return response;
} catch (error: any) {
// Handle error
}
}
); But it doesn't seem to work; the redirect happens, but the session is unchanged. |
@brunoscopelliti - thanks for raising that Your example should work, but there's an issue with I'll raise some work to fix this in the next Beta update |
Hi everyone! I apologize in advance if this isn't the appropriate place to post my question. I'm currently working on a new project using Next.js and I'm trying to implement both Auth0 SDK and next-intl simultaneously. However, I've encountered an issue where both libraries require exporting something in the middleware. I need to incorporate Auth0 into the middleware to protect all routes. I've made several attempts, but I haven't been successful in getting both libraries to work together. Here's the code that next-intl needs to export: export default createMiddleware({
locales: ["pt-br"],
defaultLocale: "pt-br",
});
export const config = {
matcher: ["/((?!api|_next|.*\\..*).*)"],
}; And here's the code that Auth0 needs to export in order to protect all routes: import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge';
export default withMiddlewareAuthRequired(); Could someone please assist me with this? I'm genuinely confused and unsure about how to proceed from this point. |
Thanks man! Works great. |
Hey there. First and foremost thank you for maintaining this awesome library. I used to have the following configuration in the import { handleAuth, handleCallback, handleLogin } from '@auth0/nextjs-auth0';
export default handleAuth({
callback: handleCallback({
afterCallback: async (req, res, session, state) => {
if (session.user) {
// In production this part is done by the Auth0 post-registration action
if (process.env.ENV && process.env.ENV === 'local') {
try {
await fetch(`${process.env.API_ENDPOINT}/signup`, {
method: 'POST',
headers: {
Authorization: `Bearer ${session.accessToken}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
idpId: session.user.sub,
email: session.user.email
})
})
} catch (e) {
console.error(`Unexpected error registering user: ${e}`)
}
}
if (session.user.email === session.user.name) {
state.returnTo = process.env.AUTH0_BASE_URL + '/profile'
}
}
return session;
}
}),
login: handleLogin({
authorizationParams: {
audience: process.env.API_ENDPOINT,
scope: 'openid email profile offline_access'
}
})
}); By using the Apparently, with the new beta this no longer works (
Request error: AccessTokenError: The user does not have a valid access token.
Request error: AccessTokenError: The user does not have a valid access token.
Request error: AccessTokenError: The user does not have a valid access token.
Request error: AccessTokenError: The user does not have a valid access token.
CallbackHandlerError: Callback handler failed. CAUSE: Missing state cookie from login request (check login URL, callback URL and cookie config).
at eval (webpack-internal:///(sc_server)/./node_modules/@auth0/nextjs-auth0/dist/handlers/callback.js:51:19)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async eval (webpack-internal:///(sc_server)/./node_modules/@auth0/nextjs-auth0/dist/handlers/auth.js:59:24)
at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:265:37) {
code: 'ERR_CALLBACK_HANDLER_FAILURE',
cause: MissingStateCookieError: Missing state cookie from login request (check login URL, callback URL and cookie config).
at eval (webpack-internal:///(sc_server)/./node_modules/@auth0/nextjs-auth0/dist/auth0-session/handlers/callback.js:18:19)
at runMicrotasks (<anonymous>)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async eval (webpack-internal:///(sc_server)/./node_modules/@auth0/nextjs-auth0/dist/handlers/callback.js:48:13)
at async eval (webpack-internal:///(sc_server)/./node_modules/@auth0/nextjs-auth0/dist/handlers/auth.js:59:24)
at async eval (webpack-internal:///(sc_server)/./node_modules/next/dist/server/future/route-modules/app-route/module.js:265:37) {
status: 400,
statusCode: 400
},
status: 400
} Not blocking us though, I'm just commenting this in case it helps. Thanks in advance! |
Also, in regards with this new release, I think it may worth adding an example of authenticating all pages below a given layout (so users don't need to place the
import '@/styles/globals.css'
import { Inter } from 'next/font/google';
const inter = Inter({
subsets: ['latin'],
variable: '--font-inter',
})
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="es">
<head>
<link rel="shortcut icon" href="/icon.svg" type="image/svg+xml"></link>
</head>
<body className={`${inter.variable} font-sans min-h-screen`}>
{children}
</body>
</html>
)
}
import { UserProvider } from "@auth0/nextjs-auth0/client";
import { withPageAuthRequired } from "@auth0/nextjs-auth0";
export default withPageAuthRequired(
async function Layout({ children }: any) {
return (
<UserProvider>
<main className={`flex flex-col justify-start items-center`}>{children}</main>
</UserProvider>
)
}
) |
Hi, do we have a timeline on when v3 will be safe for production? |
@asalcedo-ci - we're planning to release v3 by EO July |
Anyone else seeing a
|
@m-torin EDIT. Disregard what I said below ⬇️, that is not the solution 😕 I think I stumbled upon this and fix for me was to add |
Im having this error: Error: Dynamic server usage: cookies, when using this on a server page (app/page.tsx) import { getSession } from '@auth0/nextjs-auth0';
export default async function Home() {
const session = await getSession();
return <div className="container">{session?.accessToken}</div>;
} |
I found an issue with typescript My page component is like this:
It will throw an error because In this examples https://nextjs.org/docs/app/building-your-application/routing/dynamic-routes#typescript it says we can accept whatever we want for the route segments, not only slug. |
I've also got the same issue in azure where the env variables is not present at build time. Worked previously with 2.6.0 but not with 3.0.0-beta.3
|
@m-torin @milosjovancevic @phiperomega in the App Directory, Next.js is attempting to statically render the auth handlers (the auth handlers instantiate the SDK which requires the secret config). I think this is a bug in Next.js (reported here vercel/next.js#45348) because the auth handlers use the If you can't provide those env vars at build time, you should use the // /app/api/auth/[auth0]/route.ts
import { handleAuth } from '@auth0/nextjs-auth0';
export const GET = handleAuth();
export const dynamic = 'force-dynamic' @dearrolloruntim3 I'll fix the types shortly @ZainChen I don't understand your problem. Please raise a separate issue with an example repo that demonstrates your problem if you want me to investigate. |
I was getting this was apparently able to address it by adding an Here is my
|
Thanks for the response @adamjmcgrath ! Unfortunately the export const dynamic didn't work for me, produces the same error. I'm currently looking at adding the env variables at build time. |
First of all, thank you for the work on the update. We're excited to use it soon :D
I'm asking because we're incrementally adopting the app router and will only need the new |
Anyone have an idea what could cause this error? Auth flow works well in local but not in PR env. We are providing When we type email and pass and hit login button this error occurs, in callback. - ready started server on 0.0.0.0:80, url: http://localhost:80
CallbackHandlerError: Callback handler failed. CAUSE: invalid_grant (Invalid authorization code)
at /home/node/app/.next/server/chunks/514.js:1859:19
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async /home/node/app/.next/server/chunks/514.js:1762:24
at async /home/node/app/.next/server/chunks/876.js:5172:37 {
code: 'ERR_CALLBACK_HANDLER_FAILURE',
cause: IdentityProviderError: invalid_grant (Invalid authorization code)
at NodeClient.callback (/home/node/app/.next/server/chunks/514.js:160:23)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async /home/node/app/.next/server/chunks/514.js:409:29
at async /home/node/app/.next/server/chunks/514.js:1856:13
at async /home/node/app/.next/server/chunks/514.js:1762:24
at async /home/node/app/.next/server/chunks/876.js:5172:37 {
error: 'invalid_grant',
errorDescription: 'Invalid authorization code',
status: 400,
statusCode: 400,
openIdState: {
returnTo: 'this is our app domain here, just edited it :)'
}
},
status: 400
} |
Seems like the issue is, the new api routes cannot access env variables right? We will want an alternative for this to work on the v3 |
👋 v3 is now Generally Available https://github.com/auth0/nextjs-auth0/releases/tag/v3.0.0 If you notice any problems, please raise a new issue |
If anyone in the future ever runs into the issue @niksimFS24 described above. We had to increase our buffer proxy size in nginx of our k8s ingress with these two annotations: 'nginx.ingress.kubernetes.io/proxy-buffer-size': '16k',
'nginx.ingress.kubernetes.io/server-snippet': 'client_header_buffer_size 16k; large_client_header_buffers 4 32k;' |
@adamjmcgrath I'm getting following error when I try to redirect to login page
I'm currently on the free version of auth0 and also tried various ways to integrate it with my app. I tried it with both app and pages router but none of them seems to be working for me. Any help will be appreciated! |
Also encountering this issue with increasing frequency. |
@adamjmcgrath Is the Auth0 provider a server component now when using react sever components or is it a client component? |
@Sivaranjith1 - it's a client component (React Context is not available on the server) |
v3 of this SDK is now available on Beta.
The main update is support for Next.js 13.4's App Router
To install:
For more information about how to use the SDK in the app directory, see these resources:
If you notice any problems, please raise a new issue with the
beta
labelThe text was updated successfully, but these errors were encountered: