Implementing a Custom Authentication Backend in Next.js Without next-auth: A Strategic Method

Currently, I am delving into the realm of Next.js 13 for development with little familiarity in Server-Side Rendering (SSR).

The obstacle I face pertains to utilizing my own backend API built on Express.js.

This backend service already supports essential authentication functionalities such as login, signup, logout, and social login via Google.

My intention is to stick with my existing backend authentication setup instead of switching to Next.js's next-auth system. My rationale behind this decision includes:

  1. Next.js seems more geared towards frontend development rather than full-stack applications in my perspective.

  2. Given that my backend infrastructure is robustly established, I prefer leveraging its authentication features.

My current approach involves fetching cookies from the server fetch (next.js) to validate the user's login status, which has been functioning adequately so far considering my novice level.

I am interested to explore alternative methods of authenticating using my backend API without relying on next-auth. I am keen on evaluating different tactics to see if this strategy holds merit.

On the frontend side,

The cookies obtained through server-side data fetching contain JWT tokens, which I decoded to display the user's username on the navbar.

Answer №1

It seems like you're asking if authentication is possible, the answer is yes!

Authentication essentially involves using cookies in your browser to verify users. For example, I built a website with a backend in nodejs/express js. When a user logs in, a session is created (in my case using MongoDB) containing a unique identifier (UUID). This UUID is sent to the client and stored in the cookies as "session".

When a user tries to access something that requires authentication, I simply check for the existence of the cookies in the header of the request. If the cookies match a session, then the user is authenticated and can proceed. If not, I return a 403 error code with a message saying "unauthenticated". In the frontend, if the response is 403, I display a message indicating that the user is not authenticated.

If you want to check if a user is logged in when the page loads, you can create a simple API route called "user". When a token is provided but not valid, it returns a 403 error; otherwise, it returns 200 indicating successful authentication.

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

Having difficulty saving data in database using Ajax request from a Chrome extension

I am currently working on an extension that captures the page URL and saves it in a database once the user clicks the submit button. However, I have encountered a roadblock and believe there might be a missing piece in the extension setup that I cannot pi ...

Ajax encounters difficulty in parsing JSON data

I have thoroughly researched similar questions on this topic, but none of them have provided a solution to my problem. My current challenge involves parsing JSON data that is being returned from a PHP script running on the server. I have already used JSON ...

Enhance the aesthetic appeal of the imported React component with added style

I need assistance with applying different styles to an imported 'notification' component within my header component. The notification component has its own CSS style, but I want to display it in the header component with unique styling. How can I ...

Sending PDF file to client's request using PDFKIT and Strapi (Koa) via HTTP response

My goal is to send a PDF file as a response to a GET request on my Strapi endpoint. The current Strapi controller, which uses Koa, is structured like this: const PDFDocument = require("pdfkit"); module.exports = { async printOne(ctx) { const doc = ...

Tips for displaying two input decorations in Material UI beside one another within a text field

In the Text Field demonstration, I noticed input adornments at the start and end. However, I am looking to have two input adornments at the end specifically. I attempted to add them using endAdornment: {InputAdornment InputAdornment}, but encountered an er ...

Animating the Three.js Globe camera when a button is clicked

Struggling to create smooth camera movement between two points, trying to implement the function below. Currently working with the Globe from Chrome Experiments. function changeCountry(lat, lng) { var phi = (90 - lat) * Math.PI / 180; var theta = ...

What steps can I take to stop Highcharts from showing decimal intervals between x-axis ticks?

When the chart is displayed, I want to have tick marks only at integer points on the x-axis and not in between. However, no matter what settings I try, I can't seem to get rid of the in-between tick marks. Chart: new Highcharts.chart('<some i ...

Tips for minimizing the size of this script

I am new to using Jquery and Javascript, but I have managed to create a script that communicates with a php controller in symfony2. My query is, how can I shorten the script length? Is there a more efficient way to solve the logic instead of using the swi ...

Display HTML code within a data attribute

I have a function that modifies an element from OpenLayers. In the official documentation, it mentions that the property label accepts either HTML or a string. methods: { onUpdatePosition (coordinate) { this.deviceCoordinate = coordinat ...

What is the best way to create a sliding animation on a div that makes it disappear?

While I may not be an expert in animations, I have a question about sliding up the "gl_banner" div after a short delay and having the content below it move back to its original position. What CSS properties should I use for this animation? Should I use css ...

Struggling with JQuery to revert an element back to its original position after the mouseout event

Hello all, I'm a newcomer here and I've been trying my hand at some basic JQuery. However, I've encountered an issue that I could use some help with. Have you ever come across those boxes on websites where when you hover over them, an arrow ...

Leverage the power of NextJS to create a seamlessly persistent layout featuring the

Currently, I am in the process of transitioning a project from React to NextJS. The project's layout includes a common component which is a Leaflet Map. In Next JS, I utilize "next/dynamic" to load the map. Previously, React used react-router-dom@v6. ...

Should model relationships in Express.js and Mongoose be handled in the model or router?

When building a REST API with Express.js and Mongoose on Node, I encountered a code design dilemma regarding handling relationships - should it be done in models or routers? Although I am relatively new to MVC concepts, I aim to follow best design practic ...

Solving the pyramid of doom with Node.js

I have been struggling to find a way to simplify my code structure. Here is what I have come up with so far: router.use('/create', function(res,req,next) { try { var data = { startDate: new Date(req.body. ...

When sending an AJAX request to a URL, can I verify in the PHP page whether it is a request or if the page has been accessed?

In order to enhance security measures, I need to prevent users from accessing or interacting with the php pages that will be utilized for ajax functionality. Is there a method available to determine if a page has been accessed through an ajax request or b ...

Utilize the v-for second argument in VueJS 2 to showcase the index and index+1

For a VueJS 2 project, I am tasked with enhancing the display of the first and second elements in an array by making them stand out from the rest. To achieve this, I am utilizing the v-for syntax to iterate over a child component within a parent component. ...

submit the contact form information to both the database and email for further processing and storage

Currently, I have the code for connecting to a database and mail.php. I am able to save contact form data in the database successfully, but I also want to send an email to my address which I'm unsure how to do with manage_comments.php. Here are the ...

The requested method in NEXT.js 14 is not permitted

I attempted to set up a basic post API in my NEXT.js 14 application with app routing. Here is the code I used: API call: useEffect(() => { const testFunc = async () => { const response = await fetch("http://localhost:3000/helpers/ed ...

How to access additional legend labels in c3.js or billboard.js using JSON data?

I'm working with the following code snippet: ... normen is my json object .... $.each(normen, function(item) { chartX.push(this.feed_day) chartY.push(this.weight) }); createChart(char ...

The issue I am facing is that the map function is not functioning correctly when I click

I am currently working on a project in ReactJs that includes a sidebar with dropdown menu functionality. Desired Outcome When I click on an option in the sidebar that has a submenu, it should display that submenu and close upon another click. Curr ...