Protect your Vercel Next.js serverless function with secure authentication mechanisms

I'm looking to restrict access to my GraphQL API to authenticated users only. I've been using Apollo GraphQL Studio to test my API, and I've successfully set the auth token in the header. However, I'm unsure of how to retrieve and use this token in my serverless function with Next.js and Vercel.

https://i.sstatic.net/C1TWo.png

Serverless function on Vercel

export default async function handler(req: VercelRequest, res: VercelResponse) {
  console.debug(req.headers);
  console.debug(req.headers.authorization)

  res.setHeader('Access-Control-Allow-Credentials', 'true');
  res.setHeader(
    'Access-Control-Allow-Origin',
    'https://studio.apollographql.com'
  );
  res.setHeader(
    'Access-Control-Allow-Headers',
    'Origin, X-Requested-With, Content-Type, Accept'
  );

  if (req.method === 'OPTIONS') {
    res.end();
    return false;
  }

  await startLocalServer;
  await apolloServerLocal.createHandler({
    path: '/api/graphql',
  })(req, res);
}
}

export const apolloServerLocal = new ApolloServer({
  schema: schema,
  introspection: true,
});
export const startLocalServer = apolloServerLocal.start();

Output

{
  host: 'localhost:3000',
  connection: 'keep-alive',
  accept: '*/*',
  'access-control-request-method': 'POST',
  'access-control-request-headers': 'authorization,content-type',
  origin: 'https://studio.apollographql.com',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
  'sec-fetch-mode': 'cors',
  'sec-fetch-site': 'cross-site',
  'sec-fetch-dest': 'empty',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'en-US,en;q=0.9,de-DE;q=0.8,de;q=0.7'
}
undefined

Answer №1

During my application process, I took the step of configuring a shared key in Vercel's environment settings, and then in the handler function, implemented the following security measure:

// Securing the route with a secret key validation
if (
  !req.headers.authorization ||
  req.headers.authorization !== process.env.SECRET
)
  return res.status(401).send('Authorization failed');

// Add the rest of your code logic here

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

Tips for excluding files in a webpack configuration for a Vue application during the production build

I am attempting to remove an Html file named "dev.html" from the final product build. What configurations do I need to make in webpack for this? I understand that rules need to be applied, but where exactly do I need to configure them? Below is a snippe ...

I am interested in incorporating pinia state management into my Vue 3 project

I'm currently working on implementing pinia state management in Vue 3, but I've encountered the following error: Module not found: Error: Can't resolve 'src/stores/cart' in 'C:\Users\Ali Haider\theme-project&b ...

The 'exhaustive-deps' warning constantly insists on requiring the complete 'props' object instead of accepting individual 'props' methods as dependencies

This particular issue is regarding the eslint-plugin-react-hooks. While working in CodeSanbox with a React Sandbox, I noticed that I can use individual properties of the props object as dependencies for the useEffect hook: For instance, consider Example ...

The NextJS i18n feature is encountering an issue with the locale being undefined

Currently, I'm in the process of transitioning my website to NextJS, and I've run into some difficulties with internationalization. Even though I'm following the steps outlined in the official documentation, the locale displayed in the insp ...

Choosing a combination of classes

For my web application, I created checkboxes that control the visibility of windows by toggling classes on elements. My JavaScript code successfully achieves this functionality. $(document).ready(function(){ $('#field').change(function(){ ...

Tips for maintaining the state of a page submitted via Turbolinks using Rails 5 and jQuery

My current challenge involves toggling the visibility of a section when a specific element is clicked. Initially, I was able to achieve this functionality successfully. However, complications arose as my application revolves around a todo list where tasks ...

What is the best way to condense all JavaScript and CSS files in MEAN.JS for a production setting?

I recently finished creating a basic MEAN.JS application. When using MEAN.JS, I can use the command grunt build to minify the js and css files located in specific folders: css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config ...

Guide on adjusting the resolution/density of images in JPEG/PNG using JavaScript

I am looking for a way to adjust the resolution/density of JPG/PNG images using JavaScript. The purpose of this adjustment is to provide accurate metadata on the number of pixels per inch (DPI/PPI) to be used for printing by a third-party API. Is there a ...

sending the AJAX request from back to the original JavaScript function

Here presents an issue. I am dealing with an HTML Form that contains a submit button with an onclick=validationFunction(). When this button is clicked, the form values are passed to the mentioned function. Within this function, the form values undergo va ...

What is the best way to break down this function from props in React?

Forgive me if this question sounds naive, but as I delve into the world of React and useState, I am encountering a scenario where I have a signup function coded. Upon sending a username and password through a POST request to an API endpoint, a response mes ...

Extremely sluggish change identification in combination Angular application

We are encountering consistent issues with slow change detection in our hybrid AngularJS / Angular 8 app, especially when dealing with components from different versions of the framework. The problem seems to arise when using older AngularJS components wit ...

What could be the reason for the malfunction of jQuery's show() function?

Using jQuery, I have implemented a functionality to hide a div using the hide() method. However, upon clicking a link, the div is supposed to show but unexpectedly disappears after appearing briefly. HTML Code Snippet <div id="introContent"> & ...

Synchronous AJAX requests do not function properly in IE and Firefox, but they do work in Chrome and Safari

Attempting to measure download speed using an AJAX call. Below is the code snippet: var start = new Date(); $.ajax ({ url: 'https://www.example.com/perftest/dummyFile1024', cache: false, success : function() { var total = ( ...

Error: The process.binding feature is not supported in the current environment (browserify + selenium-webdriver)

Recently, I've been attempting to execute a Node.js code on the client side of my browser. To make my code compatible with browsers, I am using Browserify for conversion purposes. Below is the command I use for this transformation: browserify te ...

The map markers are nowhere to be found on the map when using Internet Explorer

Take a look at this code I wrote... var styles = [ { "featureType": "landscape", "stylers": [ {"weight": 0.1}, {"color": "#E7EDEF"} ] }, ... { "featureType": "poi.park", "elementType": "labels", "stylers": [ ...

Ways to generate an element with a specific identifier using a single line of code

When creating an element, I often use the following syntax: var foo = document.createElement('div'); To set the ID of the div, I would typically do this: foo.setAttribute('id', 'divName'); After some searching online, I ca ...

What is the best method for testing different versions of the same module simultaneously?

My goal is to distribute a module across various component manager systems like npmjs and bower. I also want to provide downloadable builds in different styles such as AMD for requirejs, commonJS, and a global namespace version for browsers - all minified. ...

The art of posting with ExpressJS

I'm encountering a problem where the data submitted through a form to my POST route is not getting passed on to a database document, even though the redirection works fine. I'm unsure of how to troubleshoot this issue. blogpost-create.ejs &l ...

Experiencing a blank page error when trying to render a partial view using Angular.js

Can someone assist me? I am encountering an issue where the partial view is not rendering properly using ui-router in Angular.js. Below is my code snippet. <!DOCTYPE html> <html lang="en" ng-app="Spesh"> <head> <meta charset="utf- ...

Saving the current date in MongoDB using the save method

Is there a way to have MongoDB automatically populate a field with the current UTC DateTime when saving a document? I'm aware of the $currentDate operator, but it seems to only be accessible within the update method. ...