DocumentationLogin
Enterspeed logo

Authentication

Enterspeed patterns

As more and more websites offer personalised services, the need for authentication becomes increasingly important.

Authentication is the process of verifying the identity of a user to ensure that they have the necessary permissions to access certain content or services. This is particularly important for websites that deal with sensitive information or offer exclusive content, such as B2B prices.

By requiring users to log in before accessing certain content, website owners can ensure that only authorised users have access to that content. This can help prevent unauthorised access to sensitive information, protect intellectual property, and ensure that only paying customers have access to premium content.

How to implement with Enterspeed

Enterspeed works as a highspeed cache which, unlike a traditional cache, also allows you to transform and combine multiple data sources into highspeed generated views.

Other than the Environment client API key, which you need to fetch from our Delivery API, there is no authentication regarding who can see what in your Delivery API.

Does this mean you can't use Enterspeed for gated/exclusive content, such as B2B prices? Not at all.

This simply means you have to handle this logic server side in your application, as you usually would anyway. One way to do it is via middleware, which we have written an article about here.

Here's an example of how this could be done in Next.js. Example borrowed from the Next.js JWT Authentication template.

1import { type NextRequest, NextResponse } from 'next/server'
2  import { verifyAuth } from '@lib/auth'
3  
4  export const config = {
5    matcher: [ '/api/protected', '/protected' ],
6  }
7  
8  export async function middleware(req: NextRequest) {
9    // validate the user is authenticated
10    const verifiedToken = await verifyAuth(req).catch((err) => {
11      console.error(err.message)
12    })
13  
14    if (!verifiedToken) {
15      // if this an API request, respond with JSON
16      if (req.nextUrl.pathname.startsWith('/api/')) {
17        return new NextResponse(
18          JSON.stringify({ 'error': { message: 'authentication required' } }),
19          { status: 401 });
20      }
21      // otherwise, redirect to the set token page
22      else {
23        return NextResponse.redirect(new URL('/', req.url))
24      }
25    }
26  }

Another way to do it is to handle the server-side logic in the individual component, which handles the gated/exclusive content, e.g. the price component. Thanks to React's new server components (RSC), this is now easier than ever since they are server-side by default – in contrast to the original client-side first paradigm we've been used to in JavaScript frameworks.

Below is an example of how we could handle customer-specific pricing using server-side logic.

1import { getByUrl } from "/lib/enterspeed";
2
3  const getProduct = async (url, isAuthenticated, userSegment) => {
4    try {
5      const product = await getByUrl(url);
6      
7      if (!product) {
8        throw new Error("Product not found");
9      }
10      
11      let { price } = product.price;
12      
13      if (!isAuthenticated) {
14        price = "Login to see price";
15      }
16      
17      if (!userSegment || !price.hasOwnProperty(userSegment)) {
18        price = price.default;
19      }
20      
21      const customerPrice = price[userSegment];
22      const salePrice = price.sale;
23      
24      if (salePrice && salePrice < customerPrice) {
25        price = salePrice;
26      }
27      
28      return {
29        ...product,
30        price,
31      };
32    } catch (error) {
33      console.error(error);
34      return {
35        error: error.message,
36      };
37    }
38  };
39  
40  export default getProduct;

Let's go through the function's actions step by step:

  1. Takes three parameters: url (a string), isAuthenticated (a boolean), and userSegment (an optional string).
  2. Attempts to fetch a product object from the Enterspeed Delivery API using the getByUrl function.
  3. If the product object is falsy (e.g. null, undefined, etc.), throws an error with the message "Product not found".
  4. Extracts the price property from the product object and assigns it to a variable.
  5. If isAuthenticated is false, sets the price variable to the string "Login to see price".
  6. If userSegment is falsy or the price object doesn't have a property matching userSegment, sets the price variable to the default property of the price object.
  7. Retrieves the price of the product based on the userSegment
  8. Retrieves the sale price of the product, if it exists.
  9. If a sale price exists and it's less than the customer price, sets the price variable to the sale price. Otherwise, sets the price variable to the customer price.
  10. Returns a new object that contains all of the properties of the original product object, as well as the price property that was just calculated.
  11. If an error occurs during the execution of the function, logs the error to the console and returns an object with an error property containing the error message.
  12. Exports the getProduct function as the default export of the module.

Ready to try out Enterspeed? 🚀

Start combining & connecting your services today

Product

Why Enterspeeed?Use casesBuild vs. buyIntegrations

Company

Partners ☕ Let's talk!About UsContact UsTerms of ServicePrivacy PolicySecurity
Enterspeed logo

© 2020 - 2024 Enterspeed A/S. All rights reserved.

Made with ❤️ and ☕ in Denmark.