Last active
October 15, 2023 11:02
-
-
Save SuaYoo/271cd0fa1803bca3ad714279fcc6e8ce to your computer and use it in GitHub Desktop.
Next.js: Update Auth0 user metadata
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AUTH0_ISSUER_BASE_URL='https://YOUR_AUTH0_DOMAIN.auth0.com' | |
AUTH0_SCOPE='openid read:current_user create:current_user_metadata update:current_user_metadata' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// api/auth/[...auth0].js | |
import { handleAuth, handleLogin } from '@auth0/nextjs-auth0'; | |
export default handleAuth({ | |
async login(req, res) { | |
try { | |
await handleLogin(req, res, { | |
authorizationParams: { | |
audience: `${process.env.AUTH0_ISSUER_BASE_URL}/api/v2/`, | |
// Need to specify scope here, for some reason nextjs-auth0 | |
// doesn't automagicallyread the scope variable from process.env | |
// like it does with other variables | |
scope: process.env.AUTH0_SCOPE, | |
}, | |
}); | |
} catch (error) { | |
res.status(error.status || 400).end(error.message); | |
} | |
}, | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// api/private/me.js | |
import axios from 'axios'; | |
import { withApiAuthRequired, getSession } from '@auth0/nextjs-auth0'; | |
import { ManagementClient } from 'auth0'; | |
const userHandler = async (req, res) => { | |
const { body } = req; | |
const session = await getSession(req, res); | |
const id = session.user.sub; | |
const accessToken = session.accessToken; | |
try { | |
const params = body; | |
const currentUserManagementClient = new ManagementClient({ | |
token: accessToken, | |
domain: process.env.AUTH0_ISSUER_BASE_URL.replace('https://', ''), | |
scope: process.env.AUTH0_SCOPE, | |
}); | |
const user = await currentUserManagementClient.updateUserMetadata( | |
{ id }, | |
params | |
); | |
res.status(200).json(params); | |
} catch (err: any) { | |
console.log(err); | |
res.status(500).json({ statusCode: 500, message: err.message }); | |
} | |
}; | |
export default withApiAuthRequired(userHandler); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment