og:image on next 14 site hosted on vercel needs an auth to display

I have deployed a Next.js 14 site on Vercel. I’ve put opengraph-image.png inside my app folder, next to layout.tsx.
When I check the meta tag in I see this:

<meta property="og:image" content="https://ns-website-6pnvd8ili-marek-migas-projects.vercel.app/opengraph-image-12o0cb.png?aadba26415c4ff29">

When I try to open that link: https://ns-website-6pnvd8ili-marek-migas-projects.vercel.app/opengraph-image-12o0cb.png?aadba26415c4ff29 it wants me to login to Vercel.
I guess that’s the reason why I can’t see that og:image ever. Do you know why it needs to auth?

useNavigate don’t work with HOC Component

This is my first question.
I am self-studying React.js, Node.js, and Express. For this reason, I am trying to create my own website where a user can register, log in, and access the page with their data only if the login is successful.

If the login is successful, a token is created using the user’s email as the payload. Additionally, I want to use a Higher Order Component (HOC) called Protect so that in my App.js file, I have something like:

<Route
  path="/ProtectedPage"
  element={<Protect component={<ProtectedPage />} />}
/>

In the handleFormSubmit function of FormLogin, I added

  navigate('/ProtectedPage');

But even if the login is successful, I don’t get any errors or redirection. It might be useful to know that Protected makes a GET request to

const verifyToken = (req, res, next) => {
  const token = req.cookies.token;

  if (!token) {
    res.status(401).send('Access Denied');
  } else {
    jwt.verify(token, secret, function (err, decoded) {
      if (err) {
        res.status(401).send('No Valid Token!');
      } else {
        req.email = decoded.email;
        req.token = token;
        console.log('verifyToken: ', req.email);
        next();
      }
    });
  }
};

app.get('/checkAuth', verifyToken, (req, res) => {
    res.sendStatus(200).send({ authenticated: true, email: req.email, token: req.token});
});

Protected.js

import React, { useState, useEffect } from 'react';
import { Navigate } from 'react-router-dom';
import axios from 'axios';

const Protect = ({ component: Component }) => {
  const [authenticated, setAuthenticated] = useState(false);

  useEffect(() => {
    // Funzione per verificare l'autenticazione
    const checkAuth = async () => {
      try {
        // Chiamata API per verificare l'autenticazione
        const response = await axios.get('http://localhost:5000/checkAuth', { withCredentials: true });
        console.log('CheckAuth Response:', response);
        // Se l'autenticazione è riuscita, imposta lo stato a true
        if (response.status === 200) {
          setAuthenticated(true);
        } else {
          setAuthenticated(false);
        }
      } catch (error) {
        console.error('Protect: Errore durante la verifica dell'autenticazione', error.response);
        setAuthenticated(false);
      }
    };

    // Chiamare la funzione di verifica dell'autenticazione al caricamento del componente
    checkAuth();
  }, []);

  // Se l'autenticazione è avvenuta con successo, rendi il componente interno
  // Altrimenti, reindirizza a /Login
  return authenticated ? <Component /> : <Navigate to="/Login" />;
};

export default Protect;

You can view my code at this link: https://github.com/CiccioLagXCVIII/MyOwnSite.git

I have already tried using console.log to verify if the data is received and sent correctly, and it is. My issue is that I don’t see any errors in the console when the login is successful, but the redirection doesn’t happen.

How to hide the bottom tab bar on the landing page in React Native

I have implemented a React Native application with a bottom tab bar using @react-navigation/material-bottom-tabs. The application also includes a stack navigator for different screens.

here’s the code for the tabbar

import React from 'react';
import 'react-native-gesture-handler';
import { Ionicons } from '@expo/vector-icons';
import LandingPage from '../screens/LandingPage';
import DisplayPage from '../screens/DisplayPage';
import StackBar from './StackBar';
import { styles } from '../styles';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';

const Tab = createMaterialBottomTabNavigator();

function TabBar() {
  return (
    <Tab.Navigator barStyle={styles.tabcontainer}>
        <Tab.Screen
          name="Home"
          component={StackBar}
          options={{
            tabBarIcon: () => <Ionicons name="home-outline" size={20} />,
          }}
        />
        <Tab.Screen
          name="Profile"
          component={DisplayPage}
          options={{
            tabBarIcon: () => <Ionicons name="person" size={20} />,
            tabBarBadge: 3,
          }}
        />
    </Tab.Navigator>
  )
}

export default TabBar

and this is for the Stack navigation

import React from 'react'
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import 'react-native-gesture-handler';
import DisplayPage from '../screens/DisplayPage';
import LandingPage from '../screens/LandingPage';

const Stack = createNativeStackNavigator();

function StackBar() {
  return (
    <Stack.Navigator>
        <Stack.Screen name="Landing" component={LandingPage} options={{ headerShown: false }} />
        <Stack.Screen name="Display" component={DisplayPage} options={{ headerShown: false, contentStyle: { backgroundColor: '#FFE5E5' } }} />
    </Stack.Navigator>
  )
}

export default StackBar

and my app.js

import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import TabBar from './components/TabBar';

export default function App() {
  return (
    <NavigationContainer>
      <TabBar/>
    </NavigationContainer>
  );
}

I want to hide the bottom tab bar only on the landing page (LandingPage). I have already tried using options={{ headerShown: false }} for the Landing screen in StackBar, but the tab bar is still visible.

What changes should I make to achieve the desired behavior, where the tab bar is hidden only on the landing page?

Any help or suggestions would be greatly appreciated! Thank you.

Need to get MUI multi select checkbox checked value

I am using this mui multi select and need to know if the item is selected or unselected to set the right state value.I checked event.target but there doesnt seem to be a checked literal

This is my mui code

<FormControl sx={{ m: 1, width: 300 }}>
    <InputLabel id="demo-multiple-checkbox-label">Tag</InputLabel>
    <Select
      labelId="demo-multiple-checkbox-label"
      id="demo-multiple-checkbox"
      multiple
      value={selectedVal}
      onChange={handleChange}
      input={<OutlinedInput label="Tag" />}
      renderValue={(selected) => selected.join(", ")}
      MenuProps={MenuProps}
    >
      {console.log(data)}
      {data.length > 0 ? (
        data.map((obj) => (
          <MenuItem
            key={obj.label + obj.accountNumber}
            value={obj.accountNumber ? obj.accountNumber : obj.label}
          >
            <Checkbox checked={selectedVal.indexOf(obj.label) > -1} />
            <ListItemText primary={obj.label} />
          </MenuItem>
        ))
      ) : (
        <MenuItem>None</MenuItem>
      )}
    </Select>
  </FormControl>

This is my change handler

  const handleChange = (event) => {
const {
  target: { value },
} = event;
console.log("value");
console.log(event["target"].checked);
setSelectedVal(
  // On autofill we get a stringified value.
  typeof value === "string" ? value.split(",") : value
);

};

Adaptive before after overlay that works on a grid in HTML

Hi I’m trying to use the following implementation of before and after image overlay in HTML:
https://www.w3schools.com/howto/howto_js_image_comparison.asp

but I can’t make it work for grid.

When I try to place it on a grid using:

<div class="row">
<div class="column">
<div class="img-comp-container">
  <div class="img-comp-img">
    <img src="img_snow.jpg" width="300" height="200">
  </div>
  <div class="img-comp-img img-comp-overlay">
    <img src="img_forest.jpg" width="300" height="200">
  </div>
</div>
<div class="img-comp-container">
  <div class="img-comp-img">
    <img src="img_snow.jpg" width="300" height="200">
  </div>
  <div class="img-comp-img img-comp-overlay">
    <img src="img_forest.jpg" width="300" height="200">
  </div>
</div>
</div>
</div>

Things are not placed next to each other as they are supposed to.
Also I would like to be able to use it with:

.row img{
  width: 100%;
}

.column img {
  padding: 0 2px;
}

So that everything is automatically rescaled to fit the page, which for now breaks the image and instead of sliding, what happens is resize of the first image.

Also adding <figcaption>Caption</figcaption> (and wrapping it with ”) doesn’t work properly placing the caption on the left and not centering it properly.

How can I fix these problems?

(in raw html)

How do I remove CSS comments use javascript?

var css = `
.test {
  background-image: url(//www.google.com/image/1.png); // goole iamge
}
@font-face {
    font-display: auto;
    font-family: vant-icon;
    font-style: normal;
    font-weight: 400;
    src: url(https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff2?t=1694918397022)
            format("woff2"),
        url("https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff?t=1694918397022")
            format("woff");
}
/**
  I‘am commonts
*/
`

Above code that I want to remove all the commoents. but it is too hard, becasue the code hava keywrok that like https://, url(//xxx). How to resolve this problem?

This is the incorrect way

var re2 = //*[sS]*?*/|(?<=[^:])//.*|^//.*/g; // incorrect

this code is incorrect

Expect

CSS code

.test {
  background-image: url(//www.google.com/image/1.png);
}
@font-face {
    font-display: auto;
    font-family: vant-icon;
    font-style: normal;
    font-weight: 400;
    src: url(https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff2?t=1694918397022)
            format("woff2"),
        url("https://at.alicdn.com/t/c/font_2553510_kfwma2yq1rs.woff?t=1694918397022")
            format("woff");
}

This code is correct. the clean-css is work, but how to use the simple way?

How to fix metadata is not set for resolving open graph and twitter in next js project

I encountered an error when running the build version in Next.js. Despite adding meta tags to the layout, the issue persists. As a Next.js newcomer, I seek guidance on resolving this issue. Any assistance or advice to troubleshoot and rectify the error would be greatly appreciated.

⚠ metadata.metadataBase is not set for resolving social open graph or twitter images, using "http://localhost:3000". See https://nextjs.org/docs/app/api-reference/functions/generate-metadata#metadatabase
Error: There is a problem with the server configuration. Check the server logs for more information.
    at getServerSession (D:isomorphic.nextserverchunks2443.js:30:19947)
    at async RootLayout (D:isomorphic.nextserverchunks9212.js:1:20494)
[Error: An error occurred in the Server Components render. The specific message is omitted in production builds to avoid leaking sensitive details. A digest property is included on this error instance which may provide additional details about the nature of the error.] {
  digest: '2927497250'
}

My layout file in app/layout.tsx

// RootLayout.js
import dynamic from 'next/dynamic';
import { Toaster } from 'react-hot-toast';
import { getServerSession } from 'next-auth/next';
import { authOptions } from '@/app/api/auth/[...nextauth]/auth-options';
import AuthProvider from '@/app/api/auth/[...nextauth]/auth-provider';
import GlobalDrawer from '@/app/shared/drawer-views/container';
import GlobalModal from '@/app/shared/modal-views/container';
import { ThemeProvider } from '@/app/shared/theme-provider';
import { siteConfig } from '@/config/site.config';
import { inter, lexendDeca } from '@/app/fonts';
import cn from '@/utils/class-names';

const NextProgress = dynamic(() => import('@/components/next-progress'), {
  ssr: false,
});
// styles
import '@/app/globals.css';

const defaultMetadata = {
  description: 'This is the description',
  openGraph: {
    title: 'Title website',
    description: 'This is the description',
    image: 'url/image.png',
  },
  twitter: {
    card: 'summary_large_image',
    site: '@eMartiiin94',
    title: 'Title website',
    description: 'This is the description',
    image: 'url/image.png',
  },
};

export const metadata = {
  title: siteConfig.title,
  ...defaultMetadata,
};

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const session = await getServerSession(authOptions);
  return (
    <html
      lang="en"
      dir="ltr"
      // required this one for next-themes, remove it if you are not using next-theme
      suppressHydrationWarning
    >
      {/* Remove the Head component */}
      <body
        // to prevent any warning that is caused by third-party extensions like Grammarly
        suppressHydrationWarning
        className={cn(inter.variable, lexendDeca.variable, 'font-inter')}
      >
        {/* Add metadata directly using the Metadata API */}
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>{metadata.title}</title>
        <meta name="description" content={metadata.description} />
        
        {/* OpenGraph Meta Tags */}
        <meta property="og:title" content={metadata.openGraph.title} />
        <meta property="og:description" content={metadata.openGraph.description} />
        <meta property="og:image" content={metadata.openGraph.image} />
        
        {/* Twitter Meta Tags */}
        <meta name="twitter:card" content={metadata.twitter.card} />
        <meta name="twitter:site" content={metadata.twitter.site} />
        <meta name="twitter:title" content={metadata.twitter.title} />
        <meta name="twitter:description" content={metadata.twitter.description} />
        <meta name="twitter:image" content={metadata.twitter.image} />

        {/* <AuthProvider session={session}> */}
          <ThemeProvider>
            <NextProgress />
            {children}
            <Toaster />
            <GlobalDrawer />
            <GlobalModal />
          </ThemeProvider>
        {/* </AuthProvider> */}
      </body>
    </html>
  );
}

Swift UI WKWebView: How do I get an alert dialog box within a website to display via a button embedded within my app

I am using a WK Web View in swift UI and the website I am displaying needs to hide the website navigation bar so that I can replace it with a native one I created within the app. The issue is that the website does not have a page for registration, rather it displays an alert dialog box asking the user to sign up from the home page.

I need to know how I would get that dialog box to appear via a native button within a navigation bar or just by clicking a button on the app (for testing purposes it does not need the nav bar yet) which is separate to the WebView.

I’ve looked into the website and the dialog box appears as the result of an event listener click which then accesses a function “app-bundle.js:####”

Chart js height limitation

I am working on displaying gantt chart using chartJS in SalesForce. I have over 2000 timeline records (bars) to be displayed. While I am able to show them, on trying to increase the height of the canvas parent container so that the labels and bars are distinctly readable, the chart breaks up.

I tried to build a simple horizontal chart in a HTML page to see if there is any limitation and to rule out any code from my project was interfering. However even on plain html, I am seeing same issue.

Is there really any limitation to the height that can be setup for the chart. Else is there any other way to increase the distance between the y axis ticks so that any two bars and labels are distinctly readable. In my requirement I also need to wrap the y axis labels hence need more space. I don’t see any padding like attribute between y axis ticks in the documentation.
Looking for some advise here.

const arrLabel = [];
const arrData = [];
for (var i = 0; i < 2000; i++) {
  arrLabel.push('Label' + i);
  arrData.push(i);
}

const data = {
  labels: arrLabel,
  datasets: [{
    label: 'Weekly Sales',
    data: arrData
  }]
};

// config 
const config = {
  type: 'bar',
  data,
  options: {
    maintainAspectRatio: false,
    responsive: true,
    indexAxis: 'y',
    scales: {
      y: {
        ticks: {
          autoSkip: false
        }
      }
    }
  }
};

// render init block
const myChart = new Chart(
  document.getElementById('myChart'),
  config
);
const num_bars = config.data.labels.length;
const bar_Height = 250 + (num_bars) * 15;
myChart.canvas.parentNode.style.height = `${bar_Height}px`;
myChart.resize();
<div style="height: 500px; max-height: 250px; overflow-y: scroll">
  <div>
    <canvas id="myChart"></canvas>
  </div>
</div>

<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.umd.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

screenshot of the chart

React fade & click through on hover

Pretty stumped on this one. I have a component that fades out when hovered upon and fades in when the mouse leaves the component. That much is simple.

But I am searching for a solution that allows the user to click through while hovering. The faded in/out component is a HUD type component that will never need to be actually clicked on and is for informational purposes.

I’ve tried various forms of pointer-events: none to no avail. That being said, I’ve tried the following in my component as well, to no avail:

const handleMouseEnter = () => {
    const overlay = document.querySelector('.timer-overlay') as HTMLElement;
    if (overlay) {
      console.log('should pass thru!');
      overlay.style.pointerEvents = 'none';
    }
  };

  const handleMouseLeave = () => {
    const overlay = document.querySelector('.timer-overlay') as HTMLElement;
    if (overlay) {
      console.log('should NOT pass thru!');
      overlay.style.pointerEvents = 'auto';
    }
  };

  return (
    <div
      className="flex timer-overlay"
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    >
      (Other components here...)
    </div>
  );

Any suggestions?

Type ‘keyof T’ cannot be used to index type ‘this’

IUser interface:

interface IUser {
  username: string;
  email: string;
  crypto: string;
}

Class User:

class User implements IUser {
  private crypto$: string;
  constructor(public username: string, public email: string, crypto: string) {
    this.crypto$ = crypto;
  }

  public get crypto(): string {
    return this.crypto$;
  }

  updateUser<T extends Partial<Omit<IUser, "crypto">>>(newUserProps: T) {
    Object.keys(newUserProps).forEach((key) => {
      const propKey = key as keyof T;
      if (this.hasOwnProperty(propKey)) {
        this[propKey] = newUserProps[propKey];
      }
    });
  }
}

I get this error: error code

PS: when I use type assertion like this (this as any)[propKey] the error dissapears, but I don’t want to use the any type

Thank You for your help!

How do I migrate unit tests written for aws-sdk v2 to aws-sdk v3?

I am currently migrating the aws-sdk v2 library to v3. Originally, the wrappers (DynamoDB put command in this case) looked like this:

const putItem = function (params: any, callback: Callback): void {
    dynamoDb.put(params, (error: DbError, data: DbData): void => {        
        callback(error, data);
    });
};

The unit test for this wrapper written in v2 looked something ike this:

test("Verify UnhandledError is thrown when failed to generate unique item Id.", async () => {
    const localPutFn = jest.fn(({}, callback) => {
        callback(expectedError, null);
    }).mockName("dynamoDb.put returns an error");

    db = mockAwsDynamoDbDocumentClient(batchWriteFn, queryFn, localPutFn, {}, scanFn);
    // This returns an instance of a database repository that has `dynamoDb.put` mocked using localPutFn

    await expect(db.putItem(testParams))
        .rejects
        .toThrow(LobbyErrorType.UnhandledError);
});

With version 3 of aws-sdk this code block has been re-written like so:

const putWrapper = function (params: any, callback: Callback): void {
    const ddbClient = new DynamoDBClient({ region: process.env.AWS_REGION, tls: true}); 
    const putCommand = new PutCommand(params);
    ddbClient.send(putCommand, (error: DbError, data) => {        
        callback(error, data);
    });
};

I am trying to rewrite the unit test to use aws-sdk-client-mock library. However, I can’t seem to figure out how to handle callback functions. This library supports a rejects and resolves feature to provide expected data or error. But how do I pass or mock callbacks like it is done for the v2 unit tests?

FabricJS setControlVisible for specific object and not for all objects of that type?

Context

I’m using Fabric.js, and I have multiple objects of the same type.

Problem

When I use obj.setControlVisible('tl', true) it enables the top left controls for all objects of that type, instead of that object specifically.

Expected or what I want to accomplish

I want to turn visible the top left control only for that specific object.

Versions

  • Fabric 3.2.0
  • React 17.0.2
  • typescript 4.8.4

Next.js dynamic routes and static builds with ID values in URL

Is there a way to create a page in Next.js where I can pull the ID from the URL in a dynamic route and use that for a static build, but not have to preset all the values of what ID can be in getStaticProps()? For instance, I have the following URL:
localhost/questions/edit/[id]
where ID can theoretically be any integer. I know for static builds you have to preset all the possible values of [id] so that next.js can generate a static HTML page for each possible value, however in my case ID values can be any number and new ID records can also be added in the future after the build.
I just would like one page for that route that can pull the dynamic ID from the URL so I can use it in my code, similar to $_GET['id'] in PHP.

I’ve tried using the regular SSR dynamic routes like Next.js intends so that the page is generated dynamically on the server, however these routes don’t work on my hosted server and I just want to try a static build before switching hosting.

I’ve found similar questions on stackoverflow like this one that use a dynamic route without getStaticProps() which seems like it might work, but I’m not sure how I should set up my file structure so that the route I listed above would point to a page file where I could then get the URL query parameter from.