Nextjs 15 uploading static website to example.com/admin

The steps I did:

  • Created Nextjs (app route) and I used ‘use client’ on every components.
  • In Dev Env The root is http://localhost:port/ .
  • npm run build, no errors and all the static files in ( out ) folder.
  • uploading part, I created a folder called admin ( example.com/admin )
  • uploaded all files in admin folder.

When I access example.com/admin, the page load for a second and then redirects me because example.com/index.txt 404 (but its exists in /admin/index.txt)

It looks for example.com/index.txt?….
where index.txt is in example.com/admin/index.txt?.. With all the files.

Next config:

const nextConfig: NextConfig = {
  env: {
    type: "production"
  },
  output: process.env.type === 'production' ? "export" : undefined,
  assetPrefix: process.env.type === 'production' ? '/admin' : '/',
  basePath: process.env.type === 'production' ? '/admin' : '',
  typescript: {
    ignoreBuildErrors: true
  }
};

export default nextConfig;

Thank you.

What is a fast combinition of language + 2d graphics library for generative art

To generate static generative art I wrote a small library in javascript. It doesn’t use p5.js, but for convenience I put it in the p5 web editor. Here is the link: Doek.js

The library works smoothly (on chrome browser) for drawing shapes and panning and zooming (the example in the link creates a huge canvas of about 23000 x 11500 pixels).

For heavy calculations however i would like to rewrite the library in another, faster programming language. But here is my problem.
Before i fully immerse myself in a new programming language, i want to know with which combination (language and 2d graphics library) i can realize this.

With the help of AI i tried different combinations (rust, c, zig, java, D, … + SDL, SFML, GLFW, …), but, although drawing the shapes works, the big problem is always copying the offscreen data from the large canvas to the window fast enough at a framerate of 60FPS.

I also tried Löve2D which worked fine, but Löve2d is very limited in drawing itself and also too slow I think (maybe i’m wrong).

processing.org can be a solution, but when the canvas is to big it is a lot slower then in js

I had no success with kotlin and openrndr either, but i am not an expert

So my question is, what combination should work. A fast programming language with a window library and a 2d graphics library (with anti aliased shapes). I do not want to generate the shapes (thin and thick lines with line caps, rectangles, arcs, ellipses, etc) myself with shaders.

I also want to mention that I work with linux (debian, arch, …)

Thanks for the advice

How to fix JS / JQUERY errors when leaving buddypress pages but still logged in

I am using buddypress on my wordpress install. Beside the buddypress pages I also have some other pages where a user can go to. But on all these “non”-buddypress pages I am getting a couple of error messages on the console like the ones below. All thrown by different buddypress plugins like better messages and others. The user ist still logged in, when viewing the other pages.

POST wp-json/better-messages/v1/checkNew?nocache=1745075303595 403
(Forbidden) (anonymous) @ bp-messages-free.min.js?ver=2.8.0:2
xhr @ bp-messages-free.min.js?ver=2.8.0:2
Ss @ bp-messages-free.min.js?ver=2.8.0:2 Promise.then
value @ bp-messages-free.min.js?ver=2.8.0:2
(anonymous) @ bp-messages-free.min.js?ver=2.8.0:2 ….

OR

Uncaught (in promise) Error: A listener indicated an asynchronous
response by returning true, but the message channel closed before a
response was received

OR

Uncaught TypeError: jQuery.cookie is not a function

The code line to the last error is

/*----------------------------------------*/
Display message after review submit
*-----------------------------------------*/
jQuery(function () {
if (jQuery.cookie("response") && jQuery.cookie("response") !== "") {
jQuery(".add_review_msg p").html(jQuery.cookie("response"));
jQuery(".add_review_msg").show();
jQuery.cookie("response", "", -1);
jQuery("#review_subject").val("");
jQuery("#review_desc").val("");
}});

What can I do to fix all these issues?

iOS Background Location Tracking Not Working in Kill Mode(React Native)

I’m currently facing an issue with background location tracking in iOS.

On Android, both foreground and background (even in kill mode) tracking work perfectly.

However, on iOS, location tracking only works in the foreground and while minimized. When the app is completely closed (kill mode), it stops tracking.

I’m using the react-native-background-actions package, and it’s not functioning as expected on iOS in background/terminated mode.

Could you please guide me or suggest a solution to enable background or terminated (kill mode) location tracking on iOS?

How to render pages with hooks for Server Side Rendering in next.js

I am familiar with React and recently started next.js for SEO optimization.

My problem is that i do not understand how to make pages static

My layout.tsx:

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <Head />
      <body>
        <UserProvider>
          <PageOverlay />
          <PageOverlayError />
          <Navbar />
          <div className="layout">
            <Sidebar />
            {children}
          </div>
        </UserProvider>
      </body>
    </html>
  );
}

As here i have UserProvider which is global context, where i store logged in user data and display/use it in components. But here as my context uses hooks it becomes client side rendered?

"use client";

...

const UserContext = createContext<UserContextType | undefined>(undefined);

export const UserProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  ...

  return (
    <UserContext.Provider value={{
      user,
      setUser,
      loadingUI,
      errorUI,
      isSidebarOpen,
      toggleSidebar,
    }}>
      {children}
    </UserContext.Provider>
  );
};

export const useUser = (): UserContextType => {
  const context = useContext(UserContext);
  if (!context) {
    throw new Error("useUser must be used within a UserProvider");
  }
  return context;
};

So as i move DOM items (in this case it would be some page.tsx content) inside <UserProvider> it automtacially becomes client side rendered? and i cannot set metadata?
Is there a way to make it server side rendered with hooks or should i use other approach?

Insert script into HTML head section when in development and not in production

I want to insert the below script tag into my popup.html and options.html when compiled in dist folder:

<script src="http://localhost:8097"></script>

I need this to be the first script before any other scripts. Below is how I expect the script to look in my HTML:

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
 <script src="http://localhost:8097"></script>
 <script src="example.js"></script>
 <script src="react.js"></script>
</head>
<body>
  
</body>
</html>

How can I go about injecting this script for local development only, when working with Webpack?

Here’s my set-up so far:

webpack.dev.js:

const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    mode: 'development',
    devtool: 'cheap-module-source-map'
});

webpack.common.js:

const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
const HtmlPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

module.exports = {
    entry: {
        popup: path.resolve('src/popup/popup.tsx'),
        options: path.resolve('src/options/options.tsx'),
        background: path.resolve('src/background/background.ts'),
        contentScript: path.resolve('src/contentScript/contentScript.js')
    },
    module: {
        rules: [
            {
                use: 'ts-loader',
                test: /.tsx?$/,
                exclude: /node_modules/
            },
            {
                use: ['style-loader', 'css-loader'],
                test: /.css$/i
            },
            {
                type: 'asset/resource',
                test: /.(jpg|jpeg|png|woff|woff2|eot|ttf|svg)$/
            }
        ]
    },
    plugins: [
        new CleanWebpackPlugin({
            cleanStaleWebpackAssets: false
        }),
        new CopyPlugin({
            patterns: [
                {
                    from: path.resolve('src/static'),
                    to: path.resolve('dist/')
                }
            ]
        }),
        ...getHtmlPlugin(['popup', 'options'])
    ],
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        filename: '[name].js',
        path: path.resolve('dist')
    },
    optimization: {
        splitChunks: {
            chunks: 'all'
        }
    }
};

function getHtmlPlugin(chunks) {
    return chunks.map(
        (chunk) =>
            new HtmlPlugin({
                title: 'Test',
                filename: `${chunk}.html`,
                chunks: [chunk]
            })
    );
}

I can’t seem to integrate my react three fiber (written jsx) with my nextjs project (written in tsx). Is there anyway to integrate them?

I created a NextJS typescript project using react 18 and I want to integrate a React Three Fiber 3D feature into it. But I keep getting

Error: Cannot read properties of undefined (reading 'ReactCurrentOwner')

I also cant upgrade to @react-three/fiber@alpha because I am on react 18 and apparently that needs react 19. Is there anyway to integrate the two together?

The code that is causing the error Overview.tsx

"use client";

import { DateRangePicker } from "@/components/ui/date-range-picker";
import { MAX_DATE_RANGE_DAYS } from "@/lib/constants";
import { UserSettings } from "@prisma/client";
import { differenceInDays, endOfMonth, startOfMonth } from "date-fns";
import React, { useState } from "react";
import { toast } from "sonner";
import StatsCards from "./StatsCards";
import CategoriesStats from "./CategoriesStats";
// import GameScene from "../../../components/GameScene";
import dynamic from "next/dynamic"; // <-- Import dynamic

const GameScene = dynamic(() => import("../../../components/GameScene"), {
  ssr: false,
});

function Overview({ userSettings }: { userSettings: UserSettings }) {
  const [dateRange, setDateRange] = useState<{ from: Date; to: Date }>({
    from: startOfMonth(new Date()),
    to: endOfMonth(new Date()),
  });
  return (
    <>
      <div className=" w-5/6 ">
        <div className="w-full px-4 flex flex-wrap items-end justify-between gap-2 py-6">
          <StatsCards
            userSettings={userSettings}
            from={dateRange.from}
            to={dateRange.to}
          />

          <div className="w-full h-150 bg-card rounded-2xl flex justify-center items-center">
            <h1>Game here</h1>
            <GameScene />
          </div>

          <h2 className="text-3xl font-bold flex flex-grow">Overview</h2>
          <div className="flex flex-grow items-center gap-3 justify-end ">
            <DateRangePicker
              initialDateFrom={dateRange.from}
              initialDateTo={dateRange.to}
              showCompare={false}
              onUpdate={(values) => {
                const { from, to } = values.range;

                if (!from || !to) return;
                if (differenceInDays(to, from) > MAX_DATE_RANGE_DAYS) {
                  toast.error(
                    `The selected date range is too big. Max allowed range is ${MAX_DATE_RANGE_DAYS}`
                  );
                  return;
                }
                setDateRange({ from, to });
              }}
            />
          </div>
        </div>
        <div className="w-full px-4 flex flex-wrap items-end justify-between gap-2 py-6 ">
          <CategoriesStats
            userSettings={userSettings}
            from={dateRange.from}
            to={dateRange.to}
          />
        </div>
      </div>
    </>
  );
}

export default Overview;

The react 3 fiber jsx component im trying to put in the overview page
GameScene.jsx

"use client";

import React, { useRef } from "react";
import { Canvas, useFrame } from "@react-three/fiber";
import * as THREE from "three"; // Type imports

function Box() {
  const ref = useRef < THREE.Mesh > null;

  useFrame(() => {
    if (ref.current) {
      ref.current.rotation.x += 0.01;
    }
  });

  return (
    <mesh ref={ref}>
      <boxGeometry args={[1, 1, 1]} />
      <meshStandardMaterial color="orange" />
    </mesh>
  );
}

function GameScene() {
  return (
    <Canvas>
      <ambientLight intensity={0.5} />
      <pointLight position={[10, 10, 10]} />
      <Box />
    </Canvas>
  );
}

export default GameScene;


What I’ve tried:

  1. changing my next.config.ts
import type { NextConfig } from "next";

const nextConfig: NextConfig = {
  /* config options here */
  transpilePackages: ["three"],
};

export default nextConfig;


  1. changing my tsconfig.json
{
  "compilerOptions": {
    "typeRoots": ["./node_modules/@types", "./src/types"],
    "target": "ES2017",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "strict": true,
    "noEmit": true,
    "esModuleInterop": true,
    "module": "esnext",
    "moduleResolution": "bundler",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "jsx": "preserve",
    "incremental": true,
    "plugins": [
      {
        "name": "next"
      }
    ],
    "paths": {
      "@/*": ["./*"]
    }
  },
  "include": [
    "next-env.d.ts",
    "**/*.ts",
    "**/*.tsx",
    ".next/types/**/*.ts",
    "next-env.d.ts",
    "src/types/**/*.d.ts",
    "components/Scene.jsx"
  ],
  "exclude": ["node_modules"]
}


Error that i am getting

Error

I’m new to Java programming but I don’t know where to start developing applications. I accept suggestions [closed]

I was taking the java course for an online course but the practical examples do not guide me to how to start thinking about developing applications in Java. Please if you can help me with suggestions. Thank you.

I understood what each concept I was taught was about, but I don’t have a guide on where to start in developing an app.

“Express.js route /api/test returns 404 when called from Next.js frontend via Axios”

  1. Problem
    I have an Express server running on port 5002 with this test endpoint:

    app.get(‘/api/test’, (req, res) => {
    res.json({ message: “Backend is working!” });
    });

Visiting http://localhost:5002/ in a browser shows the correct welcome message.

But visiting http://localhost:5002/api/test directly in a browser, Postman, or curl returns:

Cannot GET /api/test   (404 Not Found)

From my Next.js frontend (port 3000), calling the same endpoint with Axios yields:

AxiosError: Network Error
ERR_CONNECTION_REFUSED
  1. Expected Behavior
    A GET request to /api/test should return:

    { “message”: “Backend is working!” }

and the frontend Axios call should log the response without error.

  1. What I’ve Tried

Enabled CORS in Express with app.use(cors());

Bound the server to all interfaces: app.listen(PORT, ‘0.0.0.0’, …)

Cleared browser cache (Ctrl+Shift+R) and restarted both servers

Tested endpoint directly with curl and Postman (still gets 404)

  1. Relevant Code Snippets

    // server.js (Express)
    import express from ‘express’;
    import cors from ‘cors’;

    const app = express();
    app.use(cors());
    app.use(express.json());

    // Test endpoint
    app.get(‘/api/test’, (req, res) => {
    res.json({ message: “Backend is working!” });
    });

    const PORT = process.env.PORT || 5002;
    app.listen(PORT, ‘0.0.0.0’, () =>
    console.log(Server listening on port ${PORT})
    );

    // services/testConnection.ts (Next.js)
    import axios from ‘axios’;

    export const testConnection = async () => {
    return axios.get(${process.env.NEXT_PUBLIC_API_URL}/api/test);
    };

    useEffect(() => {
    testConnection()
    .then(res => console.log(‘Success:’, res.data))
    .catch(err => console.error(‘Error:’, err));
    }, []);

. Error Logs

Frontend console:

Browser/Postman:

Cannot GET /api/test   (404 Not Found)
  1. Question
    Why does my /api/test endpoint return 404 when accessed directly, and why does my Next.js frontend get ERR_CONNECTION_REFUSED?

What is the correct order for defining routes, CORS settings, and server binding so that this endpoint responds successfully to both direct and Axios requests?

How to create a cricket score ticker like this and populate it with API data in a React app?

When I was watching a live sports broadcast (cricket) on TV, I noticed an overlay showing match details with beautiful graphics and animations. It really caught my eye, and I’d love to build something similar in my React application.

My question is: How can I design and implement this kind of graphic ticker in React and how is it possible to populate it dynamically using data fetched from an API??

enter image description here

This is my attempt

export const ScoreTicker = ({ match, inningsTabs, viewStats }) => {
  console.log('score ticker match details --->>>', {
    match,
    inningsTabs,
    viewStats,
  });

  const { team1, team2, status, type } = match;
  const { roomSize } = viewStats;

  const findCurrentInning = (inningsDetails) => {
    return inningsDetails.find(
      (inning) => inning.other_details?.inning_status === 'in progress'
    );
  };

  const findFirstInning = (inningsDetails) => {
    return inningsDetails.find((inning) => inning.innings === 1);
  };

  // New function to get all innings for a specific team
  const getTeamInnings = (inningsDetails, teamId) => {
    return inningsDetails.filter((inning) => inning.team?.id === teamId);
  };

  // New function to create combined score string
  const getCombinedScore = (innings) => {
    if (!innings || innings.length === 0) return '';

    return innings
      .map((inning) => {
        const wickets = inning.details?.wickets || 0;
        const runs = inning.details?.runs || 0;
        const overs = inning.details?.overs || 0;
        const balls = inning.details?.balls || 0;

        return `${runs}/${wickets} (${overs}.${balls})`;
      })
      .join(' & ');
  };

  const currentInning = findCurrentInning(inningsTabs);
  const firstInning = findFirstInning(inningsTabs);
  const inningThisOver = currentInning?.details?.thisOver;

  // Determine team IDs
  const teamOneId = firstInning?.team?.id || match?.team1?.id;
  const teamOne = teamOneId === match?.team1?.id ? match?.team1 : match?.team2;
  const teamTwo = teamOneId === match?.team1?.id ? match?.team2 : match?.team1;

  // Get all innings for each team
  const team1Innings = getTeamInnings(inningsTabs, teamOne.id);
  const team2Innings = getTeamInnings(inningsTabs, teamTwo.id);

  // Create combined score strings
  const team1CombinedScore = getCombinedScore(team1Innings);
  const team2CombinedScore = getCombinedScore(team2Innings);
  return (
    <motion.div
      initial={{ y: 100 }}
      animate={{ y: 0 }}
      transition={{ type: 'spring', damping: 20 }}
      className="fixed bottom-0 left-0 right-0 h-32 bg-gradient-to-r from-indigo-500 via-purple-500 to-pink-500 border-t border-white/10 shadow-2xl"
    >
      <div className="w-full max-w-xl mx-auto transform transition-all duration-300 pt-2">
        {/* Match Header */}
        <div className="flex justify-between items-start mb-4 animate-fadeIn">
          <div className="flex items-center justify-center">
            <div className="flex space-x-0.5">
              <p className="text-cyan-400 text-xxs">
                {roomSize ? roomSize : 0}
              </p>
              <MatchStatusTypeDetails status={status} type={type} />
            </div>

            {/* sponsor identity */}
            <img
              src={`/sponsors/livpuro.webp`}
              alt={`Livpuro`}
              className="w-20 h-5 rounded-full object-contain"
            />
          </div>

          <div className="text-right">
            {/* match date, championship name */}
            <div className="flex items-center justify-end gap-x-2 text-xxs text-gray-200 truncate max-w-[250px]">
              {match.date}
              {match.championship.id && (
                <div className="flex items-center justify-center gap-x-1">
                  <Separator
                    orientation={`vertical`}
                    className={`w-[2px] h-3 mt-[2px] mr-1 bg-yellow-400`}
                  />
                  {match.championship.name}
                </div>
              )}
            </div>

            {/* match venue and city */}
            <div
              className="text-xxs text-gray-200 gap-x-2"
              aria-label="Match location"
            >
              {match.place?.venue}{' '}
              {match.place?.venue && match.place?.city ? ', ' : ''}{' '}
              {match.place?.city ?? 'Unknown City'}
            </div>
          </div>
        </div>

        {/* Teams Section */}
        <div className="space-y-3">
          {[
            {
              team: teamOne.name,
              logo: teamOne.logo,
              score: team1CombinedScore || teamOne.score,
            },
            {
              team: teamTwo.name,
              logo: teamTwo.logo,
              score: team2CombinedScore || teamTwo.score,
            },
          ].map(({ team, logo, score }, index) => (
            <div
              key={index}
              className="flex items-center justify-between"
              style={{ animationDelay: `${index * 100}ms` }}
            >
              <div className="flex items-center space-x-3">
                <div>
                  <img
                    src={logo.light} // Default logo for light mode
                    alt={`${team} logo`}
                    className="w-8 h-8 rounded-full object-cover dark:hidden"
                  />
                  <img
                    src={logo.dark} // Logo for dark mode
                    alt={`${team} logo`}
                    className="w-8 h-8 rounded-full object-cover hidden dark:block"
                  />
                </div>

                <span className="font-bold text-lg md:text-xl text-cyan-100">
                  {team}
                </span>
              </div>
              <span className="font-bold text-lg md:text-2xl text-cyan-100">
                {score} xx
              </span>
            </div>
          ))}
        </div>
      </div>
    </motion.div>
  );
};

it’s producing very simple design. I want something special effect like on live telecast

Securing APIs Against Unauthorized Access

We have four React Vite-based websites:

https://www.production.demo.com

https://www.production.googleteam.demo.com

https://www.production.items.demo.com

https://www.production.card.demo.com

All of these websites use a single Node.js backend.

We have implemented some basic security features such as CORS origin restrictions. However, these measures are currently not sufficient, as we’ve noticed that some users are able to access our APIs using tools like Postman or other HTTP clients by bypassing the origin check.

We’re looking for suggestions on how to further secure our APIs and prevent unauthorized access

Does onBlur see the latest state updated in onChange in React?

I’m using a React input element that has both onChange and onBlur handlers. In the onChange, I’m updating a state. Then, in onBlur, I need to use the updated value of that state.

I want to make sure the onBlur handler sees the most recent state that was set during onChange.
In my case it is working fine. But just wondering is it always guaranteed to work?

Because setState is async and the onBlur event might run before setState has run and component has rerendered?

import React, { useState } from 'react';

function MyComponent() {
  const [stateVal, setStateVal] = useState("");

  const handleChange = (e) => {
    // Update a separate piece of state
    setStateVal('random');
  };

  const handleBlur = () => {
    console.log("onBlur - stateVal:", stateVal);
    // Will this reflect the latest state set in handleChange?
  };

  return (
    <input
      onChange={handleChange}
      onBlur={handleBlur}
    />
  );
}

Penjelasan Proyek: Aplikasi Manajemen Tugas “TaskMate”

Penjelasan Proyek: Aplikasi Manajemen Tugas “TaskMate”

TaskMate adalah sebuah aplikasi manajemen tugas berbasis web yang dirancang untuk membantu pengguna dalam mengatur, memprioritaskan, dan menyelesaikan pekerjaan mereka secara lebih efisien. Proyek ini bertujuan untuk menciptakan solusi produktivitas yang sederhana namun powerful, khususnya untuk pelajar, pekerja lepas, dan tim kecil yang memerlukan alat pengelolaan tugas yang praktis.

Fitur utama TaskMate meliputi pembuatan daftar tugas, penjadwalan deadline, penetapan prioritas, serta notifikasi otomatis untuk pengingat tugas. Pengguna juga dapat membagi tugas ke dalam kategori dan menggunakan label warna untuk membedakan jenis pekerjaan. Selain itu, aplikasi ini mendukung kolaborasi tim, di mana beberapa pengguna dapat berbagi proyek, membagi tanggung jawab, serta memantau perkembangan tugas secara real-time.

Proyek ini dikembangkan menggunakan teknologi modern seperti ReactJS untuk antarmuka pengguna dan Firebase sebagai backend untuk penyimpanan data dan autentikasi. Desain UI/UX dirancang agar ramah pengguna, responsif di berbagai perangkat, dan mudah digunakan bahkan bagi pemula sekalipun.

Melalui TaskMate, kami berharap pengguna dapat meningkatkan produktivitas dan mengelola waktu mereka dengan lebih baik. Aplikasi ini juga dapat menjadi alternatif dari aplikasi sejenis yang sering kali terlalu kompleks atau berbayar. Proyek ini masih dalam tahap pengembangan dan terbuka untuk masukan pengguna guna penyempurnaan lebih lanjut.