Ensuring the safety of your NextJS SSR pages with a secure application

I am working on implementing a SSR page in nextjs, and I want to restrict access to only authenticated or logged-in users. How can I ensure this as the SSR is being generated on the server, without passing the token from local storage? Please share your thoughts 🙏

I don't have any idea how to solve this problem at the moment, so any help would be greatly appreciated.

Answer №1

In response to koolskateguy89's suggestion, one way to issue a client an access token (JWT) is by including a set-cookie header instructing the client to store the JWT as a cookie. When the client requests the specific page, remember to include the with credentials property in the request, although this may vary when using the native fetch API.

If you prefer not to utilize cookies, you can pass the authorization header and utilize the token from localstorage like so:

const res = await fetch(/api/authprotected, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${jwt-from-local-storage}`,
      },
      body: JSON.stringify(data),
    });

In the getServerSideProps function, extract and validate the JWT from the incoming request:

export const getServerSideProps: GetServerSideProps = async (context) => {
  const token =
    (context.req.headers.authorization as string) ||
    (context.req.cookies.jwt as string);

  //validate the JWT token here, send error if not authenticated

};

Keep in mind that it's recommended to handle token authorization in a centralized middleware file like middleware.ts. Avoid duplicating authorization logic across multiple api routes to adhere to the DRY principle.

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

The plugin '@next/next' failed to load while executing the npm run lint command within the GitLab CI pipeline

When running npm run lint locally on Windows, everything works fine. However, when I try to run it on my ubuntu gitlab runner, I encounter the following error: Failed to load plugin '@next/next' declared in '.eslintrc.json » eslint-config-n ...

Bringing in react to page elements in next.js (including React and CRA applications)

I have a Next.js application with multiple pages. Each page shares a similar appearance. import React, { Component } from "react"; import Wrapper from "components/Wrapper"; export default class About extends Component { render() { ...

Does using req.params in an Express.js route without any validation pose a security risk?

Is it considered a security risk to directly use the req.params.id in a route callback function? If so, what is the recommended approach to handle this situation? const express = require('express'); const app = express(); app.use('/:id&apo ...

The npm rollup.js error message reads: "ReferenceError: _default is not defined."

Struggling for hours to find a solution, as my expertise in creating modules is limited. An error message keeps popping up: ReferenceError: _default is not defined tsconfig.json { "compilerOptions": { "target": "es5", ...

When in production, Express and NextJS do not allow origin for CORS

I'm using Express and need to configure my CORS settings dynamically. My express app is running on localhost 3001, while my Next.js app is on localhost 3000. // If in production environment, allow access for Vercel app. const allowedOrigin = process. ...

Why does the error message "DeprecationWarning: 'originalKeywordKind' deprecated" keep popping up while I'm trying to compile my project?

Upon completing the compilation of my project, I encountered the error message provided below. What does this signify and what steps can I take to resolve it? - info Linting and checking validity of types DeprecationWarning: 'originalKeywordKind' ...

Start the node server, send a curl request, and then shut down the server within the Dockerfile

My Dockerfile is quite simple: FROM node:16 COPY . . RUN npm install CMD ["npm", "run", "dev"] This Dockerfile runs a NextJS application. However, I am facing an issue where I need to make two CURL Requests from the container but using them in the CMD c ...

Running Vercel's AI SDK on AWS Lambda and API Gateway: Step-by-step guide

I am currently working on deploying my NextJS Vercel AI SDK App on AWS using Cloudfront, Lambda, and API Gateway. One of the challenges I'm facing is modifying the useChat() function to incorporate the API from my Lambda Function, which handles the c ...

Encountering a Vercel deployment failure due to a TypeError: The 'split' property cannot be read from undefined within several objects

I'm having trouble deploying my web application for the first time and encountering this error on Vercel: TypeError: Cannot read property 'split' of undefined at Object.3qS3 (/vercel/path0/.next/serverless/pages/[collection]/[templateId].j ...

Tips for assigning information from a react hook within a function or event

Currently, I am in the process of learning how to create hooks in order to efficiently reuse data that needs to be modified across different components. For my project, I am utilizing Material UI's Tabs and require the use of a custom hook called use ...

Leveraging Nodemailer on Heroku

I have deployed a Next.js app with Heroku at . The app includes a contact form with a submit button that successfully sends an email when I run it locally using npm install, npm run build, npm start. However, when I try to use the app on the Heroku URL, it ...

One developer session using MongoDB with NextJS/Vercel leads to the formation of numerous connections that continue to grow exponentially

I have a Next.js app deployed on Vercel, with MongoDB connected in the Next.js api folder. Despite running just one dev session with minimal usage, the number of connections in MongoDB keeps increasing and often goes past 300 connections. I'm curious ...

Utilizing form data binding with multiple instances of forms in React

Parent Component Within my parent component, named Users, there is a snippet of code that includes the functions for adding and updating users: addUser(index, user) { var users = this.state.users var existingUser = users[index] if (existingUse ...

Bring in an asynchronous function from another file to the component

Experiencing difficulties with learning NextJs, particularly async await for fetching data from Shopify. In my file library.js, all queries are stored: const domain = process.env.API_URL const storefrontAccessToken = process.env.ACCESS_TOKEN async funct ...

The font '<URL>' was denied from loading due to its violation of the Content Security Policy directive "font-src 'none'"

I am facing a major issue with this persistent error that I can't seem to resolve. *Disclaimer: As a junior, I am still learning the ins and outs of NextJS, so please bear with me if I make any mistakes while asking this question. Currently, I am us ...

How to efficiently pass props between components in NextJs

This is the project's file structure: components ├─homepage │ ├─index.jsx ├─location │ ├─index.jsx pages │ ├─location │ │ ├─[id].jsx │ ├─presentation │ │ ├─[id].jsx │ ├─_app.jsx │ ├─index.jsx ...

I'm all set to launch my express js application! What are the major security concerns that I need to keep in

As a beginner in deploying express applications, I find myself lacking in knowledge about the essential security measures that need to be taken before launching a web application. Here are some key points regarding my website: 1) It is a simple website ...

Differences in the rendering of SVG feDiffuseLighting between Chrome and Firefox

Hey there! I encountered a strange issue with my next.js project. It has a default config and includes an SVG filter. <svg xmlns="http://www.w3.org/2000/svg"> <filter id='roughpaper'> <feTurbulence type=" ...

Establish a new data entry and link it to an already existing entry using the Prisma client (forming a one-to-one relationship)

I am currently developing a Next JS application utilizing prisma and postgresql. The database consists of 2 main tables: User and Profile Here is the schema structure for both tables: model User { id String @id @default(cuid()) name ...

My website is experiencing issues with LCP specifically on mobile devices. Instead of receiving a score, I am only presented with a question mark

After developing a website for a client, I noticed that while the desktop score was good, the mobile measurements resulted in an error. This issue could potentially impact the site's performance on Google. I suspect the animations rendered with lottie ...