Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

378
Visualizações
How to call auth0 api after log in in Next.JS?

I have a Next.JS app where I implemented auth0 login using the code from the documentation:

// pages/api/auth/[...auth0].js
import { handleAuth } from '@auth0/nextjs-auth0';

export default handleAuth();
// pages/index.js
import { useUser } from '@auth0/nextjs-auth0';

export default function Profile() {
  const { user, error, isLoading } = useUser();

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>{error.message}</div>;

  return (
    user && (
      <div>
        <img src={user.picture} alt={user.name} />
        <h2>{user.name}</h2>
        <p>{user.email}</p>
      </div>
    )
  );
}

The code is working and I am able to login. When I understand that correctly, my index.js is now protected.

Then I added an API application in auth0.

Now I created a little server in node.js:

const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
const helmet = require("helmet");
const jwt = require("express-jwt");
const jwks = require("jwks-rsa");
const authConfig = require("./auth_config.json");

const app = express();

const port = process.env.API_PORT || 3001;
const appPort = process.env.SERVER_PORT || 3000;
const appOrigin = authConfig.appOrigin || `http://localhost:${appPort}`;

if (!authConfig.domain || !authConfig.audience) {
  throw new Error(
    "Please make sure that auth__config.json is in place and poplated"
  );
}

const jwtCheck = jwt({
  secret: jwks.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: `https://${authConfig.domain}/.well-known/jwks.json`,
  }),
  audience: authConfig.audience,
  issuer: `http://${authConfig.domain}`,
  algorithms: ["RS256"],
});

app.use(morgan("dev"));
app.use(helmet());
app.use(cors({ origin: appOrigin }));
app.use(jwtCheck);

app.get("/api/protected", (reg, res) => {
  res.send({
    msg: "You called the protected endpoint!",
  });
});

app.listen(port, () => console.log(`API server listening on port ${port}`));

My question now is: How can I call the api/protected path from the index.js?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If I understand correctly, you are asking how to make an api call inside your component? If yes, below is an example.

import axios from "axios";

const yourfunctionName = async (email, password) => {
  try {
      const response = await axios.get(`http://localhost:3000/api/protected`, {
        data
      });
      return response.data
    } catch (error) {
        console.log(error.message);
      } 
};
about 4 years ago · Juan Pablo Isaza Relatório

0

Take a look at the example useFetchUser hook.

Here an HTTP call to /api/me endpoint is only sent if user is logged in.

Inside the example homepage, the user is loaded by calling the hook:

const { user, loading } = useFetchUser()

You would do something similar, however it would be slightly different since you won't need to conditionally redirect in the body of useProtectedInfo or whatever you decide to call your hook.

The structure would be broadly similar to the example.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda