What measures can be taken to prevent direct access to next-auth custom verify / error pages?

Currently, I am implementing next-auth for authentication in conjunction with an email provider. When a user enters their email address on the home page and clicks sign in, they are redirected to the localhost:3000/auth/verify page where they are instructed to check their email for further instructions.

The issue I'm facing is that individuals can access the verification page directly by simply going to localhost:3000/auth/verify, bypassing the intended workflow. This also applies to localhost:3000/auth/error.

I am wondering how I can secure these pages so they only load as part of the next-auth authentication process, triggered perhaps through the signIn() function. This is my first experience working with nextJS and next-auth overall.

In my code file pages/auth/verify.tsx:

import { Fragment } from 'react';
import { Box, Flex, Heading, Text } from '@chakra-ui/react';
import { CheckCircleIcon } from '@chakra-ui/icons';
import { useSession } from 'next-auth/react';

export default function Verify() {
  //const { data: session, status } = useSession();

  return (
    <Fragment>
      <Flex minH={'100vh'} align={'center'} justify={'center'}>
        <Box textAlign="center" py={10} px={6} maxW={'500'}>
          <CheckCircleIcon boxSize={'50px'} color={'green.500'} />
          <Heading as="h2" size="xl" mt={6} mb={2}>
            Check Your Email
          </Heading>
          <Text color={'gray.500'}>
            A verification email has been sent to your email address. Please
            check your inbox and click the link to verify your email address.
          </Text>
        </Box>
      </Flex>
    </Fragment>
  );
}

I've attempted to leverage the useSession() function to check the current status, but it only provides options like loading, authenticated, and unauthenticated, none of which fit the exact criteria I need for this scenario.

My goal is to display the verify page exclusively when the user has initiated the signIn() process within next-auth.

I would greatly appreciate any guidance or advice on best practices for handling this situation, as I may be approaching it incorrectly.

Should I consolidate everything on the login page and dynamically switch components based on progress steps? Despite researching extensively, I haven't found tutorials on this specific process.

Answer №1

If you're facing the challenge of determining where the Verify page originated from, one possible solution is to utilize the getServerSideProps function which is triggered with every request.

export async function getServerSideProps(context) {
  const willMount = context.req.headers.referer === "http://localhost:3000/example";
  if (!willMount) {
    return {
      redirect: {
        destination: "/404",
        permanent: false,
      },
    };
  }
  return {
    props: {},
  };
}

This code snippet examines whether the page was accessed from

"http://localhost:3000/example"
and redirects the user to /404 if not.

Please note that the property refer may not exist in context.req.headers if the URL was manually entered, so an alternative check method could be used like this:

if (!context.req.headers.referer)

However, the initial approach allows you to specify the acceptable URLs specifically.

In case you are working with Next.js version 13.2 and utilizing the deprecated app directory for getServerSide props, it's recommended to explore new data fetching alternatives as mentioned in the documentation.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering responsive layout design in Nextjs using Tailwind CSS

I am attempting to design a card layout where the image is on the left and the content of the card is on the right using flex in NEXTJS and Tailwind CSS. My goal is to ensure that the image remains responsive. <div className="block"> < ...

Adding react-hook-form as an external library in webpack: A step-by-step guide

I'm currently working on a form where I'm trying to integrate react-dropzone with react-hook-form. In order to achieve this, I referred to a Github discussion found here: https://github.com/react-hook-form/react-hook-form/discussions/2146. Howeve ...

Encountering a Next.js error when attempting to execute code on a live server

Encountering a frustrating error: Failed to compile ./utils/styles.js Error: failed to process internal error: entered unreachable code: assign property in object literal is invalid This annoying error popped up during the build process and can only be res ...

Error message: ".then uncaught in promise with undefined value"

myFunction() { this.initiateTSOAddressSpace().then(this.launchApp); return "placeholder text"; } sendData(contentURL: string) { let response = fetch(contentURL, { method: "POST", credentials: "include", headers: {"Accep ...

How to designate a try / catch block as asynchronous in TypeScript / JavaScript?

I am facing an issue where the code is not entering the catch block in case of an error, try { this.doSomething(); } catch (error) { console.error(error); } This problem occurs when "doSomething" returns a promise or runs asynchronous code. doSome ...

Mesh clipping during rotation

After creating a model using meshes in three.js, I noticed that some of the meshes clip when I move my camera with OrbitControls. The rendered image shows the issue: https://i.sstatic.net/gBidu.gif Researching online, I came across a solution suggesting ...

The outcome of a promise is an undefined value

I am facing an issue where I need to access the result of my API call outside the promise, but the value I receive is always undefined. Within the OrderService : public async getOrderPrice(device: string) : Promise<any> { this.urlOrderPrice = th ...

Ways to retrieve class variables within a callback in Typescript

Here is the code I'm currently working with: import {Page} from 'ionic-angular'; import {BLE} from 'ionic-native'; @Page({ templateUrl: 'build/pages/list/list.html' }) export class ListPage { devices: Array<{nam ...

Inheritance from WebElement in WebdriverIO: A Beginner's Guide

I am seeking a solution to extend the functionality of the WebElement object returned by webdriverio, without resorting to monkey-patching and with TypeScript type support for autocompletion. Is it possible to achieve this in any way? class CustomCheckb ...

Iterating through an array with ngFor to display each item based on its index

I'm working with an ngFor loop that iterates through a list of objects known as configs and displays data for each object. In addition to the configs list, I have an array in my TypeScript file that I want to include in the display. This array always ...

Loading text not displaying in Angular 2 mobile app

I have developed an angular2 application using typescript that relies on SystemJS. My starting point was this seed app I found. When viewed on a desktop, you can observe the loading text enclosed within tags (e.g. Loading...). On the index page of my app ...

I am having trouble with my jest-cucumber test not properly recognizing my step definitions

I recently started using the jest-cucumber library to execute my jest tests in BDD format. However, when I try running a sample test, I encounter the following issue: ? Given Test for given step Undefined. Implement with the following snippet: ...

What is the syntax for passing a generic type to an anonymous function in a TypeScript TSX file?

The issue lies with the function below, which is causing a failure within a .tsx file: export const enhanceComponent = <T>(Component: React.ComponentType<T>) => (props: any) => ( <customContext.Consumer> {addCustomData => ...

What is preventing me from accessing a JavaScript object property when using a reactive statement in Svelte 3?

Recently, while working on a project with Svelte 3, I encountered this interesting piece of code: REPL: <script lang="ts"> const players = { men: { john: "high", bob: "low", }, }; // const pl ...

What is causing this issue in TypeScript version 4.8?

After updating to TypeScript 4.8 in VSCode, I have encountered an error in one of my React projects that was not present before. Strangely, this error does not prevent the code from compiling successfully when building the project. It's challenging to ...

Loss of image quality when utilizing Next/Image in NEXT JS

I am currently developing a web application using Next.js 13, and I recently noticed a decrease in the quality of my images. I'm not sure what went wrong or what I may have missed. Upon inspecting the HTML element on the browser, I found this code: & ...

A unique directive that showcases both default and custom errors sequentially

In my project, I am facing a challenge where I need to compare the input text with a series of inbuilt errors such as required, minlength, maxlength, and pattern. Additionally, I also need to validate the input against a custom condition using a Custom Val ...

Steps for preloading a user prior to the page loading

Main Concern I currently have an Auth Provider set up in my application that wraps around the entire _app.tsx file. This allows me to utilize the "useAuth" hook and access the user object from any part of the app. However, I am facing an issue when using ...

Angular - Error: Object returned from response does not match the expected type of 'request?: HttpRequest<any>'

While working on implementing an AuthGuard in Angular, I encountered the following Error: Type 'typeof AuthServiceService' is not assignable to type '(request?: HttpRequest) => string | Promise'. Type 'typeof AuthServiceServic ...

Is there a way to renew a token when utilizing msal-node for Microsoft Integration?

Currently, I am utilizing the @azure/msal library in combination with Microsoft Graph APIs within a Confidential Client Application. After successfully configuring the initial flow and obtaining the access token through cca.acquireTokenByCode(), I have enc ...