If your Express app shows a blank tab icon, the file may exist but never be served publicly or linked in the page head. This Express JS favicon guide uses static middleware and standard HTML links.
Prerequisites
Prepare a square brand mark. Mzu favicondl can create an SVG, an ICO fallback, and an optional Apple touch PNG.
You also need:
- A running Express app.
- Access to the shared HTML layout or
public/index.html. - The command that starts your app, such as
npm start.
Express JS favicon setup
Create a public directory
Place browser-facing assets in public at the project root:
my-app/
├─ public/
│ ├─ favicon.svg
│ ├─ favicon.ico
│ ├─ apple-touch-icon.png
│ └─ index.html
└─ app.js
Keep filenames exact because Linux servers distinguish uppercase and lowercase characters.
Serve the public directory
Register static middleware before application routes and any catch-all 404 handler:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, () => {
console.log('Listening on http://localhost:3000');
});
Express now maps public/favicon.svg to /favicon.svg and can serve public/index.html at /. A route placed before static middleware can answer the icon request first.
Link the icons in the HTML head
Add explicit links to the shared layout so every route receives them:
<head>
<link rel='icon' href='/favicon.svg' type='image/svg+xml'>
<link rel='icon' href='/favicon.ico' sizes='16x16 32x32 48x48'>
<link rel='apple-touch-icon' href='/apple-touch-icon.png'>
</head>
The HTML Standard defines rel='icon' as an external resource link, so these tags give browsers an explicit icon URL.
Verify the files and rendered HTML
Restart the server, then request both files:
curl -I http://localhost:3000/favicon.svg
curl -I http://localhost:3000/favicon.ico
Both requests should return HTTP 200. Confirm that the page source contains the same paths; if the files respond but the tab still looks wrong, use the favicon troubleshooting checklist.
Publish icon updates safely
When the icon changes, update the HTML URL to href='/favicon.svg?v=2' and increment the version on each deployment. A filename hash also works and avoids reusing the old URL; the cache-busting guide explains the trade-offs.
Common Express pitfalls
- Wrong directory: files in
src are not public unless express.static points there. - Wrong order: a catch-all route before
express.static can block icon requests. - One page only: put links in the EJS, Pug, or HTML layout, not one route.
- Subpath deployment: root-relative
/favicon.svg can miss an app mounted below a prefix; build URLs from the public base path.
Conclusion
Keep the asset path, static middleware, and shared HTML links aligned. That gives every Express route the same favicon without a dedicated icon controller.
Express 앱의 탭 아이콘이 비어 보인다면 파일이 존재하더라도 서버에서 제공되지 않았거나 페이지 head에 link되지 않았을 수 있습니다. 이 Express JS favicon 가이드는 static middleware와 표준 HTML link를 사용합니다.
필수 조건
정사각형 브랜드 마크를 준비합니다. Mzu favicondl을 사용하면 SVG와 ICO fallback 파일을 만들고, 선택적으로 Apple touch PNG를 추가할 수 있습니다.
다음 항목이 필요합니다.
- 실행 중인 Express 앱.
- 공유 HTML 레이아웃 또는
public/index.html에 접근할 수 있어야 합니다. - 앱을 시작하는 명령이 필요합니다(예:
npm start).
Express JS favicon 설정
public 디렉터리 생성
프로젝트 루트의 public에 브라우저에 제공할 애셋을 다음과 같이 배치합니다.
my-app/
├─ public/
│ ├─ favicon.svg
│ ├─ favicon.ico
│ ├─ apple-touch-icon.png
│ └─ index.html
└─ app.js
Linux 서버는 대문자와 소문자를 구분하므로 파일명을 정확히 유지해야 합니다.
public 디렉터리 제공
애플리케이션 라우트와 catch-all 404 핸들러보다 먼저 static middleware를 다음과 같이 등록합니다.
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, () => {
console.log('Listening on http://localhost:3000');
});
이제 Express는 public/favicon.svg를 /favicon.svg에 매핑하며 public/index.html 파일을 /에서 제공할 수 있습니다. static middleware보다 앞에 배치된 라우트는 아이콘 요청을 먼저 처리할 수 있습니다.
HTML head에 아이콘 연결
모든 라우트에 아이콘이 적용되도록 공유 레이아웃에 명시적인 link를 다음과 같이 추가합니다.
<head>
<link rel='icon' href='/favicon.svg' type='image/svg+xml'>
<link rel='icon' href='/favicon.ico' sizes='16x16 32x32 48x48'>
<link rel='apple-touch-icon' href='/apple-touch-icon.png'>
</head>
HTML Standard는 rel='icon'을 외부 리소스 link로 정의합니다. 따라서 이 태그들은 브라우저에 명시적인 아이콘 URL을 제공합니다.
파일과 렌더링된 HTML 확인
서버를 다시 시작합니다. 다음 명령으로 두 파일을 요청합니다.
curl -I http://localhost:3000/favicon.svg
curl -I http://localhost:3000/favicon.ico
두 요청 모두 HTTP 200 응답이 반환되어야 합니다. 페이지 소스에 동일한 경로가 포함되어 있는지 확인합니다. 파일 요청이 정상적으로 처리되는데도 탭 아이콘이 여전히 잘못 표시된다면 favicon 문제 해결 체크리스트를 사용합니다.
아이콘 변경 사항 안전하게 게시하기
아이콘이 변경되면 HTML의 URL을 href='/favicon.svg?v=2'로 업데이트하고, 배포할 때마다 버전을 증가시킵니다. 파일명 해시를 사용하는 방식도 가능합니다. 이 방식은 이전 URL을 재사용하지 않습니다. cache-busting 가이드에서 trade-off을 설명합니다.
Express에서 자주 발생하는 문제
- 잘못된 디렉터리:
src 안에 있는 파일은 express.static이 해당 경로를 가리키지 않으면 공개되지 않습니다. - 순서 오류:
express.static보다 앞에 catch-all route를 두면 favicon 요청을 가로챌 수 있습니다. - 한 페이지에만 적용: EJS, Pug 또는 HTML layout에 링크를 넣어야 하며, 특정 route 하나에만 넣는 것이 아닙니다.
- Subpath 배포: root-relative
/favicon.svg는 prefix 아래에 배포된 앱에서는 찾지 못할 수 있으므로, public base path에서 URL을 생성해야 합니다.
결론
asset 경로, static middleware, 공유 HTML 링크를 일치시키세요. 그러면 전용 icon controller 없이도 모든 Express route에서 동일한 favicon을 사용할 수 있습니다.
Si tu aplicación Express muestra un icono de pestaña en blanco, puede que el archivo exista pero nunca se exponga públicamente o no esté enlazado en el head de la página. Esta guía de Express JS favicon utiliza static middleware y enlaces HTML estándar.
Requisitos previos
Prepara una imagen de marca cuadrada. Mzu favicondl puede crear un SVG, un ICO como fallback y un PNG opcional de Apple touch.
También necesitas:
- Una aplicación Express en funcionamiento.
- Acceso al layout HTML compartido o a
public/index.html. - El comando que inicia tu aplicación, como
npm start.
Configuración del favicon en Express JS
Crea un directorio public
Coloca los assets destinados al navegador en public, en la raíz del proyecto:
my-app/
├─ public/
│ ├─ favicon.svg
│ ├─ favicon.ico
│ ├─ apple-touch-icon.png
│ └─ index.html
└─ app.js
Mantén los nombres de archivo exactamente como son, porque los servidores Linux distinguen entre mayúsculas y minúsculas.
Expón el directorio public
Registra el static middleware antes que las rutas de la aplicación y cualquier controlador 404 catch-all:
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
app.listen(3000, () => {
console.log('Listening on http://localhost:3000');
});
Express ahora asigna public/favicon.svg a /favicon.svg y puede servir public/index.html en /. Una ruta situada antes del static middleware puede responder primero a la solicitud del icono.
Enlaza los iconos en el head del HTML
Añade enlaces explícitos al layout compartido para que todas las rutas los reciban:
<head>
<link rel='icon' href='/favicon.svg' type='image/svg+xml'>
<link rel='icon' href='/favicon.ico' sizes='16x16 32x32 48x48'>
<link rel='apple-touch-icon' href='/apple-touch-icon.png'>
</head>
El HTML Standard define rel='icon' como un enlace a un recurso externo, por lo que estas etiquetas indican a los navegadores una URL explícita para el icono.
Verifica los archivos y el HTML generado
Reinicia el servidor y solicita los dos archivos:
curl -I http://localhost:3000/favicon.svg
curl -I http://localhost:3000/favicon.ico
Ambas solicitudes deberían devolver HTTP 200. Confirma que el código fuente de la página contiene las mismas rutas; si los archivos responden pero la pestaña sigue mostrando un aspecto incorrecto, consulta la lista de resolución de problemas del favicon.
Publica las actualizaciones del icono de forma segura
Cuando cambie el icono, actualiza la URL del HTML a href='/favicon.svg?v=2' e incrementa la versión en cada deployment. También puedes añadir un hash al nombre del archivo para evitar reutilizar la URL anterior; la guía de cache-busting explica los trade-offs.
Errores comunes en Express
- Directorio incorrecto: los archivos en
src no son públicos a menos que express.static apunte a ese directorio. - Orden incorrecto: una ruta catch-all situada antes de
express.static puede bloquear las solicitudes del icono. - Solo una página: coloca los enlaces en el layout de EJS, Pug o HTML, no en una sola ruta.
- Despliegue en un subpath: una ruta root-relative como
/favicon.svg puede no encontrarse si la app está montada bajo un prefijo; construye las URL a partir del public base path.
Conclusión
Mantén alineados la ruta del asset, el middleware estático y los enlaces compartidos en el HTML. Así, todas las rutas de Express usarán el mismo favicon sin necesidad de un controlador dedicado para el icono.
Prepare your Express favicon files
Convert your brand mark into SVG, ICO, and PNG assets with Mzu favicondl, then deploy them from your Express public folder.
Try It Free →