Next.js Discord

Discord Forum

NextJS 13 & Auth0 API Authentication

Unanswered
British Shorthair posted this in #help-forum
Open in Discord
British ShorthairOP
Was just hoping for some assistance from anyone who has successfully implemented NextJS13 and Auth0 SDK to authenticate the user and then use the authenticated state to restrict API calls. To my understanding the Auth0 NestJS sdk does not have a session Token or cookie so there is odd ways to go about doing what needs to be done.

My current and not working implementation is;

apiClient.ts
import axios from "axios";
import { getAccessToken } from "./authService";

const apiClient = axios.create({
  baseURL: "http://localhost:3001",
});

apiClient.interceptors.request.use((config) => {
  const accessToken = getAccessToken();

  if (accessToken) {
    config.headers.Authorization = `Bearer ${accessToken}`;
  }

  return config;
});

export default apiClient;



authService.ts
import { useUser } from "@auth0/nextjs-auth0/client";

export const useAuth = () => {
  const { user, error, isLoading } = useUser();

  return { user, error, isLoading };
};

export const isAuthenticated = () => {
  const { user } = useUser();
  return !!user;
};

export const setAccessToken = (accessToken: string) => {
  localStorage.setItem("access_token", accessToken);
};

export const getAccessToken = () => {
  return localStorage.getItem("access_token");
};

3 Replies

The better way instead of using access tokens would be to use WithApiAuthRequired()
@British Shorthair is your problem solved?