Auth0 Login on Next.js

Has anyone else tried to set Auth0 in the Refine Next.js version? I'm having trouble to accomplish the same effect, as the refine doc is based on React https://refine.dev/docs/advanced-tutorials/auth/auth0/. I tried to adapt following the Auth0 doc https://auth0.com/docs/quickstart/webapp/nextjs/01-login. The odd thing is it also have to move the authProvider inside the App component to access a hook through:
const App = () => {
const { isLoading, isAuthenticated, user, logout, getIdTokenClaims } =
useAuth0(); // <- this one

if (isLoading) {
return <span>loading...</span>;
}

const authProvider: AuthProvider = {
login: () => {
...
const App = () => {
const { isLoading, isAuthenticated, user, logout, getIdTokenClaims } =
useAuth0(); // <- this one

if (isLoading) {
return <span>loading...</span>;
}

const authProvider: AuthProvider = {
login: () => {
...
The Next.js version uses another hook called useUser, but still, I have a dependency of the authProvider in the [[...refine]].tsx file. I'd appreciate anyone's help, thanks.
R
rare-sapphireβ€’483d ago
Can you reproduce the issue ? Stackblitz or GitHub repo will be awesome. We will look into it as a first thing tomorrow
A
adverse-sapphireβ€’483d ago
https://github.com/Daniel-Boll/auth0-login-next I have not provided the Auth0 secrets, if you guys happen to need it contact me. Also I have not changed the authProvider because the experiments I was doing might be so wrong that will only confuse you guys. I left some @here markers to the important places
R
rare-sapphireβ€’482d ago
thank you so much πŸ™ @danielboll, you need to move authProvider inside <App> because useAuth() cannot work outside react component. i'm trying to create nextjs example with auth0. but auth0 sdk have issues with nextjs 13 at the moment. im looking for workaround to work with refine data-provider. i will inform you when i found work around https://github.com/auth0/nextjs-auth0/issues/889
A
adverse-sapphireβ€’482d ago
Yeah, but the [[...refine]].tsx also needs the authProvider, that's where I got stuck on. Okay, thank you for you effort, if you need anything else I'm happy to help
R
rare-sapphireβ€’482d ago
We are investigating the issue. We will inform you as soon as possible
A
adverse-sapphireβ€’481d ago
βœ” Choose a project template Β· refine-react βœ” Choose your backend service to connect: Β· data-provider-custom-json-rest βœ” Do you want to use a UI Framework?: Β· mui βœ” Do you want to customize the Material UI theme?: Β· mui-extend-theme βœ” Do you want to customize the Material UI layout?: Β· mui-custom-layout βœ” Do you want to add dark mode support?: Β· mui-dark-mode βœ” Do you need any Authentication logic?: Β· auth-provider-auth0 βœ” Do you need i18n (Internationalization) support?: Β· i18n-mui βœ” Do you want to add example pages?: Β· mui-example-pages βœ” Do you want to add kbar command interface support?: Β· kbar βœ” Choose a package manager: Β· pnpm βœ” Would you mind sending us your choices so that we can improve superplate? Β· yes I also tried with the React version using the CLI as shown, as it is just inserting my credentials in the AuthProvider also doesn't work, I login, but cannot access /posts for example, still stuck to the /login altough logged
R
rare-sapphireβ€’481d ago
Hi @danielboll, i created PR for you https://github.com/Daniel-Boll/auth0-login-next/pull/1 but there are some bad practice this is sending request on every route change. to solve this, maybe you should only check hasCookie ? Promise.resolve() : Promise.reject() and your backend should validate auth0 token and return 401 or 403. after that u can implement ideal logic on authPRovider.checkError
checkAuth: async (params) => {
const cookies = nookies.get(params)

try {
const res = await axios.get(`http://localhost:3000/api/auth/me`, {
headers: {
cookie: `appSession=${cookies['appSession']}`,
},
})
return res.status === 200 ? Promise.resolve() : Promise.reject()
} catch (error) {
return Promise.reject()
}
}
checkAuth: async (params) => {
const cookies = nookies.get(params)

try {
const res = await axios.get(`http://localhost:3000/api/auth/me`, {
headers: {
cookie: `appSession=${cookies['appSession']}`,
},
})
return res.status === 200 ? Promise.resolve() : Promise.reject()
} catch (error) {
return Promise.reject()
}
}
After auth sdk release nextjs13 fix. we will write documentation for full example. also we have https://next-auth.js.org/ implementation in our backlog.
A
adverse-sapphireβ€’481d ago
Thank you @alicanerdurmaz, I will try it ASAP. NextAuth will eventually be a great addition to Refine, which is already awesome πŸ˜ƒ About this problem on Auth0 and React, should I create another topic?
R
rare-sapphireβ€’481d ago
of course. thank you for helping us ! πŸ™
A
adverse-sapphireβ€’481d ago
And thank you for helping me!
R
rare-sapphireβ€’481d ago
i run this example on my machine https://refine.dev/docs/advanced-tutorials/auth/auth0/ it's works as expected. what is your error output ? did you change Auth0Provider props ? src/index.ts
<React.StrictMode>
<Auth0Provider
domain='dev-0s583yip.us.auth0.com'
clientId='nB61Zm0BP0YqyrbiHdMxtrMHyAPmEZFU'
redirectUri={window.location.origin}>
<App />
</Auth0Provider>
</React.StrictMode>
<React.StrictMode>
<Auth0Provider
domain='dev-0s583yip.us.auth0.com'
clientId='nB61Zm0BP0YqyrbiHdMxtrMHyAPmEZFU'
redirectUri={window.location.origin}>
<App />
</Auth0Provider>
</React.StrictMode>
A
adverse-sapphireβ€’481d ago
Yeah, running this one works fine, but if I create a new refine-CRA app with the auth0 as a AuthProvider it doesn't
R
rare-sapphireβ€’481d ago
ohh sorry. i will check with this options
A
adverse-sapphireβ€’481d ago
Yep, the Auth0-party works fine I even indeed log-in, but I think there's a problem with the authProvider it do not detect that I have the authentication I tried tying the authProvider with a dependency array of something from the useAuth0 through useMemo, without success tho
R
rare-sapphireβ€’481d ago
useMemo not necessary. in the example, checkAuth looks for token. if token exist, it assumes you are authenticated.
checkAuth: async () => {
try {
const token = await getIdTokenClaims()
if (token) {
axios.defaults.headers.common = {
Authorization: `Bearer ${token.__raw}`,
}
return Promise.resolve()
} else {
return Promise.reject()
}
} catch (error) {
return Promise.reject()
}
},
checkAuth: async () => {
try {
const token = await getIdTokenClaims()
if (token) {
axios.defaults.headers.common = {
Authorization: `Bearer ${token.__raw}`,
}
return Promise.resolve()
} else {
return Promise.reject()
}
} catch (error) {
return Promise.reject()
}
},
backend should determine do you have auth or not and should return 403 or 401 . after that for example, if 403 you should refresh tokens, if 401 you should logout.
checkError: () => Promise.resolve(),
checkError: () => Promise.resolve(),
How is the scenario where authProvider doesn't work properly? i delete tokens from chrome. i redirected to login page
A
adverse-sapphireβ€’481d ago
But when you logged in you get to the /posts page for instance?
R
rare-sapphireβ€’481d ago
yes i did
A
adverse-sapphireβ€’481d ago
Wow πŸ˜΅β€πŸ’« I don't I'll try creating the project again
R
rare-sapphireβ€’481d ago
i tried https://refine.dev/docs/advanced-tutorials/auth/auth0/ this i didn't check npm create refine-app yet. i use example repo now i will try to debug this
A
adverse-sapphireβ€’481d ago
Oh, right, my problem was exactly in this scenario, using the advanced tutorial worked for me as well
R
rare-sapphireβ€’481d ago
okay i will check and return you asapπŸ™ @danielboll hi again, can you add this to App.tsx
if (isLoading) {
return <span>loading...</span>;
}
if (isLoading) {
return <span>loading...</span>;
}
you can add here
function App() {
const { isLoading, user, logout, getIdTokenClaims } = useAuth0()
const { t, i18n } = useTranslation()

if (isLoading) {
return <span>loading...</span>
}

const authProvider: AuthProvider = {

---
---
function App() {
const { isLoading, user, logout, getIdTokenClaims } = useAuth0()
const { t, i18n } = useTranslation()

if (isLoading) {
return <span>loading...</span>
}

const authProvider: AuthProvider = {

---
---
this problem occurs becase useAuth0 try to login, but still in loading state. that means getIdTokenClaims() returns undefined and we are redirecting to login page we will fix npm create refine app template. thank you πŸ™
A
adverse-sapphireβ€’481d ago
Niiiice, now it works You were very kind and helpful, thank you so much πŸ™
R
rare-sapphireβ€’481d ago
im glad to hear that πŸ™ thank you for your clear explanation the issues
O
Omerβ€’392d ago
Hey @danielboll , Hope you're doing well. We released our NextAuth.js example today. If you're still interested, you can take a look at it here: https://refine.dev/docs/examples/next-js/NextAuth.js/.
Authentication with NextAuth.js | refine
refine allows you to build your SSR supported web applications using Next.js. With this example, you can see how to make a simple refine app in Next.js and NextAuth.js with Authentication features.
More Posts
mapping relationships in Refine Airtable for Headless approachHello, I wish to ask if there’s a sample for implementing mapping of relationships in refine-airtablHow to format currency in mui input ?Hi πŸ‘‹ I have an API which return me prices in cents and i would like to format this value in an ipublog-ecommerce is broken since 3 days agoThe example blog-ecommerce is broken since a few days ago. Not sure why, maybe chakra-ui conflicts wHow to change the Refine logo in the sider barHi all, Please tell me How to change the default Refine logo in the sider bar with my own logo? Can Compile Error After Update Refine and AntdI just update refine and other things but i got error. Could you help me please?useImport ExcelHi there! new to the refine.dev can somebody help me here, general design let's say, how can I do anCompiled Error when update refine antdI just update refine antd from refine update command and got this error.How to use generic search with strapi-v4 and useTableHi πŸ‘‹ I am listing the customers from my database with useTable hook from AntD and Strapi-v4 as datHello to everyone!I would like to understand if it's possible to add filter params to URL in the List view. I want touseSelect fetch on scrollit's me again!) How to use scroll pagination with select via useSelect hook? Maybe you have any exammake a new call api after the x-locale changeHello i'm currently making an app with refine and i have implement i18n. I also have an API which aldeleting successfully but showing errorerror notification on settledNavigation not properly working if the resource has custom routeHi, I am using react-router-6, We have configured a resource with a route called '/config/units'. whhasura data provider - pass token in header before requestI've configured my hasura endpoint so that an Authrization Header must be populated with a value (i.useDelete hook and useTableHi guys, i use useTable hook to fetch data and take only one element from list via id in initial filExample storefront brokenhttps://example.refine.dev/1/Starters link seems brokenDefault Login Page does not exit, and I can't create my login pageI added authProvider, Exit button added to the interface automatically, but login page doesn’t existBroken drawer after update to new antd versionYesterday i updated refine-antd from 3.6.1 to 4.1 and my nested drawers got stacked in data containUpgrade from antd 4 to 5 got a weird sider.I have upgraded my antd package from 4 to 5 and now my side bar looks weird with black and white porhistory.pushcan i use history.push("/customroute',{data:"something"}) in refine and i want to access that in us