Skip to content

Instantly share code, notes, and snippets.

@SuaYoo
Last active October 15, 2023 11:02
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SuaYoo/271cd0fa1803bca3ad714279fcc6e8ce to your computer and use it in GitHub Desktop.
Save SuaYoo/271cd0fa1803bca3ad714279fcc6e8ce to your computer and use it in GitHub Desktop.
Next.js: Update Auth0 user metadata
AUTH0_ISSUER_BASE_URL='https://YOUR_AUTH0_DOMAIN.auth0.com'
AUTH0_SCOPE='openid read:current_user create:current_user_metadata update:current_user_metadata'
// 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);
}
},
});
// 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